package org.bigdata.framework.admin.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.io.FileUtils;
import org.bigdata.framework.admin.web.util.DBUtils;
import org.bigdata.framework.admin.web.util.DateUtils;
import org.bigdata.framework.admin.web.util.FileDownloadUtil;
import org.bigdata.framework.admin.web.util.Letter;
import org.bigdata.framework.admin.web.util.MD5;
import org.bigdata.framework.core.model.Classes;
import org.bigdata.framework.core.model.DataProperty;
import org.bigdata.framework.core.model.DataSource;
import org.bigdata.framework.core.model.Department;
import org.bigdata.framework.core.model.Dict;
import org.bigdata.framework.core.model.DictItem;
import org.bigdata.framework.core.model.GeneralWord;
import org.bigdata.framework.core.model.GeneralWordCategory;
import org.bigdata.framework.core.model.Log;
import org.bigdata.framework.core.model.ThesauriWord;
import org.bigdata.framework.core.model.ThesauriWordCategory;
import org.bigdata.framework.core.model.ThesauriWordModule;
import org.bigdata.framework.core.model.ThesauriWordReference;
import org.bigdata.framework.core.model.ThesauriWordRelation;
import org.bigdata.framework.core.model.User;
import org.bigdata.framework.core.model.UserGroup;
import org.bigdata.framework.core.model.UserGroupRole;
import org.bigdata.framework.core.model.UserGroupUser;
import org.bigdata.framework.core.model.UserRole;
import org.bigdata.framework.core.protocol.IBaseService;
import org.bigdata.framework.core.protocol.IDynamicService;
import org.bigdata.framework.core.protocol.IPublicService;
import org.bigdata.framework.core.protocol.IWordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.code.kaptcha.Constants;
import com.xxl.conf.core.XxlConfClient;

/**
 * 用户 管理 字典类管理 知识分类 管理
 */
@Controller
public class SystemController extends BaseContoroller {

	@Autowired
	private IBaseService baseService;
	@Autowired
	private IPublicService publicService;
	@Autowired
	private IWordService iWordService;
	@Autowired
	private IDynamicService dynamicService;
	
	@RequestMapping("system-list.html")
	public void getSystemList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		List r = dynamicService.getSystemList();
		String resultString = formatToJson(r);
		System.out.println("resultString=" + resultString);
		super.pringWriterToPage(resultString, "application/json", response);
	}
	
	@RequestMapping("module-list.html")
	public void getModuleList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String systemEn = request.getParameter("systemEn");
		List r = dynamicService.getModuleList(systemEn);
		String resultString = formatToJson(r);
		System.out.println("resultString=" + resultString);
		super.pringWriterToPage(resultString, "application/json", response);
	}
	
	@RequestMapping("task-list.html")
	public void getTaskList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String systemEn = request.getParameter("systemEn");
		String moduleEn = request.getParameter("moduleEn");
		List r = dynamicService.getTaskList(systemEn, moduleEn);
		String resultString = formatToJson(r);
		System.out.println("resultString=" + resultString);
		super.pringWriterToPage(resultString, "application/json", response);
	}

	// 公共日常记录
	public void Log(Integer createUserId, String logType, String classesId,
			String dataId, String logText, Integer logStatus) throws Exception {
		// 获得本机IP
		InetAddress addr = InetAddress.getLocalHost();
		String createIpAddress = addr.getHostAddress();
		// 获得时间
		String createTime = DateUtils.getDateTime();

		Log log = new Log();
		log.setCreateTime(createTime);
		log.setCreateUserId(createUserId);
		log.setCreateIpAddress(createIpAddress);
		log.setLogType(logType);
		log.setLogText(logText);
		log.setLogStatus(logStatus);

		if (classesId != null) {
			log.setClassesId(classesId);
		}
		if (dataId != null) {
			log.setDataId(dataId);
		}
		baseService.saveLog(log);
	}

	// geren_geRen_ziLiao.html
	@RequestMapping("geren-geRen-ziLiao.html")
	public String gerenGeRenZiLiao() {
		return "/modules/repository/geren_geRen_ziLiao";
	}

	// 系统管理 -->用户管理-->默认跳转 查询页面
	@RequestMapping("user-guan-li.html")
	public String toUserGuanLi() {
		return "/modules/repository/user_guan_li";
	}

	// 系统管理 -->用户管理-->更新 新增 页面
	@RequestMapping("user-add-update.html")
	public String toUserAddAndUpdate() {
		return "/modules/repository/user_add_update";
	}

	// 系统管理 -->用户管理-->更新 新增 页面 树形部门查询
	@RequestMapping("user-editSave-department-zTree.html")
	public String touserEditSaveDepartmentZTree() {
		return "/modules/repository/user_editSave_department_zTree";
	}

	// 系统管理 -->用户管理-->更新 新增 页面 树形部门查询
	@RequestMapping("user-editSave-userGroup-zTree.html")
	public String userEditSaveUserGroupZTree() {
		return "/modules/repository/user_editSave_userGroup_zTree";
	}

	// 知识字典管理 --> 默认跳转 查询字典类
	@RequestMapping("show-findall-dict.html")
	public String toShowFindDict() {
		return "/modules/repository/show_findall_dict";
	}

	// 知识字典管理 --> 默认跳转 查询字典类 --> 跳转 字典项查询 【普通结构(名称-值)】
	@RequestMapping("show-findall-dictitem-biaoge.html")
	public String toShowDindDictitemBiaoge() {
		return "/modules/repository/show_findall_dictitem_biaoge";
	}

	// 知识字典管理 --> 默认跳转 查询字典类 --> 跳转 插入 新增 字典 数据
	@RequestMapping("dict-add-update.html")
	public String toDictAddUpdate() {
		return "/modules/repository/dict_add_update";
	}

	// 知识字典管理 --> 默认跳转 查询字典类 --> 跳转 字典项查询 【普通结构(名称-值)】--> 跳转 插入 —— 新增 字典项 【表结构】
	// 数据
	@RequestMapping("dictItem-add-updateBiao.html")
	public String todictItemaddupdate() {
		return "/modules/repository/dictItem_add_updateBiao";
	}

	// 知识字典管理 --> 默认跳转 查询字典类 --> 跳转 查询字典项类 【树形结构】
	@RequestMapping("show-findall-dictitem-zTree.html")
	public String tofindalldictitemZTree() {
		return "/modules/repository/show_findall_dictitem_zTree";
	}

	// 知识字典管理 --> 默认跳转 查询字典类 --> 跳转 查询字典项类 【树形结构】 --> 更新 新增 字典项【树型结构】
	@RequestMapping("dictItem-add-updateZTree.html")
	public String todictItemAddUpdateZTree() {
		return "/modules/repository/dictItem_add_updateZTree";
	}

	// 知识字典管理 --> 默认跳转 查询字典类 --> 跳转 查询字典项类 【树形结构】 --> 更新 新增 字典项【树型结构】 -->获取树形菜单
	@RequestMapping("dictItem-save-edit-findall-zTree.html")
	public String toDictItemSaveEditFindallZTree() {
		return "/modules/repository/dictItem_save_edit_findall_zTree";
	}

	// 知识分类列表
	@RequestMapping("knowledge-category-list.html")
	public String toKnowledgeCategoryList() {
		return "/modules/repository/knowledge_category_list";
	}

	// 知识分类列表 父节点
	@RequestMapping("domain-save-edit-findall-zTree.html")
	public String toDomainZTree() {
		return "/modules/repository/domain_save_edit_findall_zTree";
	}

	// 数据源列表
	@RequestMapping("user-source-list.html")
	public String toDataSourceList() {
		return "/modules/repository/data_source_list";
	}

	// 数据源 新增修改 管理
	@RequestMapping("data-source-addEntity.html")
	public String toDataSourceaddEdit() {
		return "/modules/repository/data_source_addEntity";
	}

	// 数据接口列表
	@RequestMapping("data-interface-list.html")
	public String toDataInterfaceList() {
		return "/modules/repository/data_interface_list";
	}

	// 数据接口 在线调试列表
	@RequestMapping("data-interface-debug.html")
	public String toDataInterfaceDebug() {
		return "/modules/repository/data_interface_debug";
	}

	// 普通词表管理主页面
	@RequestMapping("word-general-list.html")
	public String toWordGeneralList() {

		return "/modules/word/word_general_list";
	}

	// 普通词表 增加 修改页面
	@RequestMapping("word-general-addEdit.html")
	public String wordGeneralAddEdit() {
		return "/modules/word/word_general_addEdit";
	}

	// 普通词表 分类管理查询窗口
	@RequestMapping("word-generalWordCategory-list.html")
	public String wordGeneralWordCategoryList() {
		return "/modules/word/word_generalWordCategory_list";
	}

	// 分类管理添加 修改
	@RequestMapping("word-generalWordCategory-addEdit.html")
	public String wordGeneralWordCategoryaddEdit() {
		return "/modules/word/word_generalWordCategory_addEdit";
	}

	//
	@RequestMapping("word-general-import.html")
	public String wordGeneralImport() {
		return "/modules/word/word_general_import";
	}

	// 叙词表管理主页面
	@RequestMapping("word-thesaurus-list.html")
	public ModelAndView toWordThesaurusList(HttpServletRequest request,HttpServletResponse response) {
	    String id = request.getParameter("id");
	    List<LinkedHashMap<String, Object>> r = new ArrayList<LinkedHashMap<String, Object>>();
	    List<ThesauriWordModule> thesauriWordModuleList = iWordService.getThesauriWordModule();
	    LinkedHashMap<String, Object> data = null;
	    for (int i = 0; i < thesauriWordModuleList.size(); i++) {
	        ThesauriWordModule thesauriWordModule = thesauriWordModuleList.get(i);
            data = new LinkedHashMap<String, Object>();
            data.put("id", thesauriWordModule.getId());
            data.put("nameZh", thesauriWordModule.getNameZh());
            if( null != id && id.equals(thesauriWordModule.getId().toString())){
                data.put("selected", "selected");
            }else{
                data.put("selected", " ");
            }
            r.add(data);
        }
	    ModelAndView view = new ModelAndView();
        view.addObject("thesauriWordModule", r);
        view.setViewName("/modules/word/word_thesaurus_list");
        return view;
	}

	// 叙词表(主题款目词表) 添加 修改
	@RequestMapping("word-thesauriWord-addEdit.html")
	public ModelAndView wordThesauriWordAddEdit() {
	    ModelAndView view = new ModelAndView();
        view.addObject("thesauriWordModule", iWordService.getThesauriWordModule());
        view.setViewName("/modules/word/word_thesauriWord_addEdit");
        return view;
	    
	}

	// 叙词表(主题款目词表) 范畴查询
	@RequestMapping("word-thesauriWordCategory-zTree.html")
	public String towordThesauriWordCategoryZTree() {
		return "/modules/word/word_thesauriWordCategory_zTree";
	}

	// 叙词表(主题款目词表) 范畴 添加 修改
	@RequestMapping("word-thesauriWordCategory-zTreeAddEdit.html")
	public String towordThesauriWordCategoryZTreeAddEdit() {
		return "/modules/word/word_thesauriWordCategory_zTreeAddEdit";
	}

	// 叙词表(主题款目词表) 范畴 父节点
	@RequestMapping("word-thesauriWordCategoryAddEditFind-zTree.html")
	public String towordThesauriWordCategoryAddEditFindZTree() {
		return "/modules/word/word_thesauriWordCategoryAddEditFind_zTree";
	}

	// 叙词表 款目词参照项 添加 编辑 关联
	@RequestMapping("word-thesauriWordReference-addEdit.html")
	public ModelAndView towordThesauriWordReferenceAddEdit(HttpServletRequest request,
            HttpServletResponse response) {
	   String classes = request.getParameter("classes");
	   HashMap<String, Object> queryParams = new LinkedHashMap<String, Object>();
	   queryParams.put("=,thesauri_word_module_id", classes);
	   List<ThesauriWordRelation> thesauriWordRelationLsit =  iWordService.getThesauriWordRelation(queryParams, 1, iWordService.getThesauriWordRelationCount(queryParams));
	   String relation = "";
	   for (int i = 0; i < thesauriWordRelationLsit.size(); i++) {
	       ThesauriWordRelation thesauriWordRelation = thesauriWordRelationLsit.get(i);
	       relation += thesauriWordRelation.getNameEn()+";";
	   }
	   if(null != relation && !"".equals(relation)){
	       relation = relation.substring(0, relation.length()-1);
	   }
	   ModelAndView view = new ModelAndView();
       view.addObject("thesauriWordModule", iWordService.getThesauriWordModule());
       view.addObject("thesauriWordRelationLsit", thesauriWordRelationLsit);
       view.addObject("relation", relation);
       view.setViewName("/modules/word/word_thesauriWordReference_addEdit");
       return view;
	}

	// 叙词表 列表式管理叙词表 根据范畴查询
	@RequestMapping("select_thesauriWordCategory_zTree.html")
	public String toselectThesauriWordCategory() {
		return "/modules/word/select_thesauriWordCategory_zTree";
	}

	// 叙词表 图形化显示
	@RequestMapping("word-thesaurus-find-ReferenceSave.html")
	public String towordThesaurusFindReferenceSave() {
		return "/modules/word/word_thesaurus_find_ReferenceSave";
	}

	// 日志
	@RequestMapping("user-menu-logGuanLi.html")
	public ModelAndView tologGuanLi() {
		ModelAndView view = new ModelAndView();
		view.addObject("userList", publicService.getUser());
		view.setViewName("/modules/repository/log_guanLi");
		return view;
	}
	// 叙词表 图形化显示
	@RequestMapping("word-thesauriWord-junior.html")
	public String toWordThesauriWordJunior() {
		return "/modules/word/word_thesauriWord_junior";
	}

	Integer newUserId; // 所登录的用户ID

	private Object transformer;

	/**
	 * 实现 用户管理
	 */
	// 系统管理 -->用户管理 -->默认查询页面
	@RequestMapping("userfindAll")
	@ResponseBody
	public void userfindAll(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		Integer pageNumber = 15;
		Integer pageSize = Integer.parseInt(request.getParameter("page"));
		String queryParam = request.getParameter("queryParams");
		String text = request.getParameter("text");

		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if (text != null && !"".equals(text)) {
			queryParams.put("%," + queryParam, text);
		}
		Integer count = publicService.getUserCount(queryParams);
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		List<User> list = publicService.getUser(queryParams, pageSize,
				pageNumber);
		for (int i = 0; i < list.size(); i++) {
			User aUser = list.get(i);
			mp = new LinkedHashMap<String, Object>();
			mp.put("id", aUser.getId());
			mp.put("username", aUser.getUsername());
			mp.put("password", aUser.getPassword());
			mp.put("nickname", aUser.getNickname());
			mp.put("telephone", aUser.getTelephone());
			mp.put("address", aUser.getAddress());
			mp.put("email", aUser.getEmail());
			if (aUser.getDepartmentId() != null
					&& !"".equals(aUser.getDepartmentId())) {
				Department department = publicService.findDepartment(aUser
						.getDepartmentId());
				mp.put("departmentName", department.getName());
			} else {
				mp.put("departmentName", "");
			}
			String date = "null";
			if (aUser.getCreateTime() != null
					&& !aUser.getCreateTime().equals("")) {
				date = aUser.getCreateTime();
			}
			mp.put("createTime", date);
			mp.put("signature", aUser.getSignature());
			r.add(mp);
		}

		String result = formatToJson(r);
		StringBuffer sb = new StringBuffer();
		int listsize = r.size();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 系统管理 -->用户管理 -->添加 and 更新用户
	@RequestMapping("userAddandUpdate")
	@ResponseBody
	public void userAdd(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// System.out.println("useraddupdate() User 更新 添加");
		User user = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		String id = request.getParameter("id");
		if ("-1".equals(id)) {
			id = request.getSession().getAttribute("userid").toString();
		}
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String nickname = request.getParameter("nickname");
		String telephone = request.getParameter("telephone");
		String address = request.getParameter("address");
		String email = request.getParameter("email");
		String departmentId = request.getParameter("departmentId");
		String createTime = request.getParameter("createTime").trim();
		String signature = request.getParameter("signature");
		String userGroupId = request.getParameter("userGroupId");
		int status = Integer.parseInt(request.getParameter("status"));
		// System.out.println(userGroupId);
		String ugId[] = userGroupId.split(",");
		User u = new User();
		u.setUsername(username);
		u.setNickname(nickname);
		u.setCreateTime(createTime);
		u.setTelephone(telephone);
		u.setAddress(address);
		u.setEmail(email);
		u.setDepartmentId(Integer.parseInt(departmentId));
		u.setSignature(signature);
		u.setIsPrincipal(status);
		User u2 = new User();
		UserGroupUser uGu = null;
		if (!id.equals("0") && !id.equals("0") && id != null) {
			HashMap<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("=,userId", id);
			List<UserGroupUser> listGroup = publicService
					.getUserGroupUser(queryParams);

			for (UserGroupUser userGroupUser : listGroup) {
				// System.out.println("uguid: " +
				// userGroupUser.getUserGroupId());
				List<UserGroupRole> listUserGR = publicService
						.getUserGroupRole();
				String str = "";

				for (UserGroupRole ugrs : listUserGR) {
					if (ugrs.getUserGroupId().equals(
							userGroupUser.getUserGroupId())) {
						str = ugrs.getRoleIds();
						if (!"".equals(str)) {
							str = str.substring(0, str.length() - 1);
							String strSplit[] = str.split(":");
							// System.out.println("str    " + str);
							for (int i = 0; i < strSplit.length; i++) {
								List<UserRole> ur = publicService.getUserRole();
								for (int k = 0; k < ur.size(); k++) {
									UserRole r = ur.get(k);
									if (r.getUserId() == userGroupUser
											.getUserId()
											&& r.getRoleId() == Integer
													.parseInt(strSplit[i])) {
										baseService.deleteUserRole(r);
									}
								}
							}
						}
					}

				}
				baseService.deleteUserGroupUser(userGroupUser);
			}

			for (int i = 0; i < ugId.length; i++) {
				uGu = new UserGroupUser();
				uGu.setUserId(Integer.parseInt(id));
				uGu.setUserGroupId(Integer.parseInt(ugId[i]));
				baseService.saveUserGroupUser(uGu);
				List<UserGroupRole> listugr = publicService.getUserGroupRole();

				for (int k = 0; k < listugr.size(); k++) {
					String str = "";
					UserGroupRole ugr = listugr.get(k);
					if (ugr.getUserGroupId() == Integer.parseInt(ugId[i])) {
						str = ugr.getRoleIds();
						if (!"".equals(str)) {
							str = str.substring(0, str.length() - 1);
							String strSplit[] = str.split(":");
							for (int j = 0; j < strSplit.length; j++) {
								UserRole userRole = new UserRole();
								userRole.setRoleId(Integer
										.parseInt(strSplit[j]));
								userRole.setUserId(Integer.parseInt(id));
								baseService.saveUserRole(userRole);
							}

						}
					}
				}
			}
			u = publicService.findUser(Integer.parseInt(id));
			u.setUsername(username);
			u.setNickname(nickname);
			u.setCreateTime(createTime);
			u.setTelephone(telephone);
			u.setAddress(address);
			u.setEmail(email);
			u.setDepartmentId(Integer.parseInt(departmentId));
			u.setSignature(signature);
			u.setIsPrincipal(status);
			if (!"".equals(password) && password != null) {
				u.setPassword(MD5.convert(password));
			}
			u.setId(Integer.parseInt(id));
			int logTime = 0;
			try {
				u2 = baseService.editUser(u);
			} catch (Exception e) {
				this.Log(user.getId(), "general_data", null, null,
						"【" + user.getNickname() + "】【修改】用户【" + username
								+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(user.getId(), "general_data", null, null,
						"【" + user.getNickname() + "】【修改】用户【" + username
								+ "】成功！", 0);
			}

		} else if (id.equals("0")) {
			u.setPassword(MD5.convert(password));
			int logTime = 0;
			try {
				u2 = baseService.saveUser(u);
			} catch (Exception e) {
				this.Log(user.getId(), "general_data", null, null,
						"【" + user.getNickname() + "】【新增】用户【" + username
								+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(user.getId(), "general_data", null, null,
						"【" + user.getNickname() + "】【新增】用户【" + username
								+ "】成功！", 0);
			}

			HashMap<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("=,username", u2.getUsername());
			List<User> ulist = publicService.getUser(queryParams, 1, 1);
			User u3 = ulist.get(0);
			// System.out.print(ulist.size() + "	" +
			// ulist.get(0).getNickname());
			for (int i = 0; i < ugId.length; i++) {
				// System.out.print(ugId[i] + "	");
				uGu = new UserGroupUser();
				uGu.setUserId(u3.getId());
				uGu.setUserGroupId(Integer.parseInt(ugId[i]));
				uGu = baseService.saveUserGroupUser(uGu);
				// System.out.println("id"+uGu.getId());
				List<UserGroupRole> listugr = publicService.getUserGroupRole();

				for (int k = 0; k < listugr.size(); k++) {
					String str = "";
					UserGroupRole ugr = listugr.get(k);
					if (ugr.getUserGroupId() == Integer.parseInt(ugId[i])) {
						str = ugr.getRoleIds();
						// System.out.print(str + "	" + str);
						if (!"".equals(str)) {
							str = str.substring(0, str.length() - 1);
							String strSplit[] = str.split(":");
							for (int j = 0; j < strSplit.length; j++) {
								UserRole userRole = new UserRole();
								userRole.setRoleId(Integer
										.parseInt(strSplit[j]));
								userRole.setUserId(u3.getId());
								baseService.saveUserRole(userRole);
							}

						}
					}
				}

			}
		}
		String result = formatToJson(u2);
		// System.out.println("resultadd：" + result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 判断用户名不能重复
	@RequestMapping("UserPanDuan")
	@ResponseBody
	public void toUserPanDuan(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String username = request.getParameter("username").trim();
		LinkedHashMap<String, Object> mp = new LinkedHashMap<String, Object>();
		List<User> list = publicService.getUser();
		for (int i = 0; i < list.size(); i++) {
			User user = list.get(i);
			if (username.equals(user.getUsername())) {
				mp.put("tishi", "0");
				break;
			} else {
				mp.put("tishi", "1");
			}
		}
		String result = formatToJson(mp);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 获取更新内容 并显示到网页
	@RequestMapping("userfindone")
	public void toUserFindOne(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		Integer id = Integer.parseInt(request.getParameter("id"));
		if (id == -1) {
			id = (Integer) request.getSession().getAttribute("userid");
		}
		HashMap<String, Object> userMap = new HashMap<String, Object>();
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("=,userId", id);
		String userGroupId = "";
		String userGroupName = "";
		List<UserGroupUser> listGroup = publicService
				.getUserGroupUser(queryParams);
		for (UserGroupUser userGroupUser : listGroup) {
			userGroupId += userGroupUser.getUserGroupId() + ",";
			UserGroup ug = publicService.findUserGroup(userGroupUser
					.getUserGroupId());
			userGroupName += ug.getName() + ",";
		}
		// System.out.println(userGroupName.length());
		if (listGroup.size() >= 1) {
			userGroupId = userGroupId.substring(0, userGroupId.length() - 1);
			userGroupName = userGroupName.substring(0,
					userGroupName.length() - 1);
		}
		userMap.put("userGroupId", userGroupId);
		userMap.put("userGroupName", userGroupName);
		User user = publicService.findUser(id);
		if (user != null) {
			userMap.put("username", user.getUsername());
			userMap.put("password", user.getPassword());
			userMap.put("nickname", user.getNickname());
			userMap.put("telephone", user.getTelephone());
			userMap.put("address", user.getAddress());
			userMap.put("email", user.getEmail());
			userMap.put("status", user.getIsPrincipal());
			if (user.getDepartmentId() != null) {
				Department department = publicService.findDepartment(user
						.getDepartmentId());
				userMap.put("departmentId", department.getId());
				userMap.put("departmentName", department.getName());
			}

			String date = "null";
			if (user.getCreateTime() != null && user.getCreateTime() != "") {
				date = user.getCreateTime();
			}
			userMap.put("createTime", date);
			userMap.put("signature", user.getSignature());
		}
		String result = formatToJson(userMap);
		// System.out.println("result  "+result);
		super.pringWriterToPage(result.toString(), "application/json", response);

	}

	// 删除单个用户
	@RequestMapping("userdel")
	public void toUserDel(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer id = Integer.parseInt(request.getParameter("id"));
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("=,userId", id);
		List<UserGroupUser> listGroup = publicService.getUserGroupUser(queryParams);
		for (UserGroupUser userGroupUser : listGroup) {
			baseService.deleteUserGroupUser(userGroupUser);
		}
		List<UserRole> listUserRole = publicService.getUserRole(queryParams);
		for (UserRole ur : listUserRole) {
			baseService.deleteUserRole(ur);
		}
		User user = new User();
		user = publicService.findUser(id);
		int logTime = 0;
		User logUser = publicService.findUser((Integer) request.getSession().getAttribute("userid"));
		try {
			baseService.deleteUser(user);
		} catch (Exception e) {
			this.Log(
					logUser.getId(),
					"general_data",
					null,
					null,
					"【" + logUser.getNickname() + "】【删除】用户【"
							+ user.getUsername() + "】失败！请检查数据是否正确！", 1);
			logTime = 1;
			e.printStackTrace();
		}
		if (logTime == 0) {
			this.Log(
					logUser.getId(),
					"general_data",
					null,
					null,
					"【" + logUser.getNickname() + "】【删除】用户【"
							+ user.getUsername() + "】成功！", 0);
		}

		String result = formatToJson(user);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 获取当前时间
	@RequestMapping("newDate")
	public void toNewDate(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(new java.util.Date());
		String result = "{\"date\":\"" + date + "\"}";
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	/**
	 * 实现 字典类 管理
	 */

	// 字典类查询所有
	@RequestMapping("DictListall")
	public void toDictListall(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		List<Dict> Dict1 = publicService.getDict();
		String result = formatToJson(Dict1);
		// System.out.println("DictListall   "+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 字典类查询
	@RequestMapping("findallDict")
	@ResponseBody
	public void findAllDict(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("findallDict");
		Integer pageNumber = 15;
		Integer pageSize = 1;
		if (request.getParameter("page") != null) {
			pageSize = Integer.parseInt(request.getParameter("page"));
		} else {
			pageSize = 1;
		}
		String queryParam = request.getParameter("queryParams");
		String text = request.getParameter("text");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if (text != null && !"".equals(text)) {
			queryParams.put("%," + queryParam, text);
		}
		Integer count = publicService.getDictCount(queryParams);
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		List<Dict> list = publicService.getDict(queryParams, pageSize,pageNumber);
		List<Dict> dictAll = publicService.getDict();
		for (int i = 0; i < list.size(); i++) {
			Dict dict = list.get(i);
			if (dict != null) {
				mp = new LinkedHashMap<String, Object>();
				mp.put("id", dict.getId());
				mp.put("nameZh", dict.getNameZh());
				mp.put("nameEn", dict.getNameEn());
				mp.put("dictType", dict.getDictType());
				if (dict.getDictType() == 1) {
					mp.put("dictType", "普通结构(名称-值)");
					mp.put("tiaozhuan", "showDictitemBiaoge");
				} else if (dict.getDictType() == 2) {
					mp.put("dictType", "树形结构");
					mp.put("tiaozhuan", "showDictitemzTree");
				} else {
					mp.put("dictType", "null");
				}
				mp.put("sort", dict.getSort());
				r.add(mp);
			}
		}

		String result = formatToJson(r);
		// System.out.println("result:" +result);
		StringBuffer sb = new StringBuffer();
		int listsize = list.size();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"sortMuch\":" + dictAll.get((dictAll.size()-1)).getSort() + ",");
		sb.append("\"pageSize\":"+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 删除字典类单条数据
	@RequestMapping("deldict")
	public void toDictDelOne(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("=,dictId", id);
		Integer count = publicService.getDictItemCount(queryParams);
		Dict dict = publicService.findDict(Integer.parseInt(id));
		List<Classes> listClasses = publicService.getClasses();
		List<DictItem> dictItem = publicService.getDictItem(dict);
		boolean falg = false;
		for (Classes classes : listClasses) {
			List<DataProperty> dataPropertiesList = publicService
					.getDataProperty(classes);
			for (DataProperty dataProperty : dataPropertiesList) {
				if (dataProperty.getDictId() == Integer.parseInt(id)) {
					falg = true;
					break;
				}
			}
			if (falg == true) {
				break;
			}
		}
		if (falg == false) {
			  if(dictItem.size()>0){ 
				  for (int i = 0; i < dictItem.size(); i++) {
					  baseService.deleteDictItem(dictItem.get(i));
			 
				  } 
			  }
			int logTime = 0;
			User user = publicService.findUser((Integer) request.getSession()
					.getAttribute("userid"));
			try {
					baseService.deleteDict(dict);
			} catch (Exception e) {
				this.Log(
						user.getId(),
						"general_data",
						null,
						null,
						"【" + user.getNickname() + "】【删除】字典【"
								+ dict.getNameZh() + "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(
						user.getId(),
						"general_data",
						null,
						null,
						"【" + user.getNickname() + "】【删除】字典【"
								+ dict.getNameZh() + "】成功！", 0);
			}

		}
		String result = "{\"count\":" + falg + "}";
		// System.out.println("reult dict 删除字典类单条数据: "+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	// 删除字典类选中数据
	@RequestMapping("deleteDictAll")
	public void deleteDictAll(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String ids [] = request.getParameterValues("valueIds");
		List<Classes> listClasses = publicService.getClasses();
		User user = publicService.findUser((Integer) request.getSession().getAttribute("userid"));
		String r = "yes";
		for (int i = 0; i < ids.length; i++) {
			String id = ids[i];
			Dict dict = publicService.findDict(Integer.parseInt(id));
			List<DictItem> dictItem = publicService.getDictItem(dict);
			boolean falg = false;
			for (Classes classes : listClasses) {
				List<DataProperty> dataPropertiesList = publicService.getDataProperty(classes);
				for (DataProperty dataProperty : dataPropertiesList) {
					if (dataProperty.getDictId() == Integer.parseInt(id)) {
						falg = true;
						break;
					}
				}
				if (falg == true) {
					break;
				}
			}
			if (falg == false) {
				if(null != dictItem && dictItem.size()>0){ 
					for (int j = 0; j < dictItem.size(); j++) {
						baseService.deleteDictItem(dictItem.get(j));
					} 
				}
				int logTime = 0;
				try {
					baseService.deleteDict(dict);
				} catch (Exception e) {
					r = "no";
					this.Log(
							user.getId(),
							"general_data",
							null,
							null,
							"【" + user.getNickname() + "】【删除】字典【"
									+ dict.getNameZh() + "】失败！请检查数据是否正确！", 1);
					logTime = 1;
					e.printStackTrace();
				}
				if (logTime == 0) {
					this.Log(
							user.getId(),
							"general_data",
							null,
							null,
							"【" + user.getNickname() + "】【删除】字典【"
									+ dict.getNameZh() + "】成功！", 0);
				}
				
			}
		}
		
		HashMap<String, Object> rMap = new HashMap<String, Object>();
		rMap.put("data", r);
		String result = formatToJson(rMap);
		// System.out.println("reult dict 删除字典类单条数据: "+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 插入 更新 字典 数据
	@RequestMapping("dictAddandUpdate")
	@ResponseBody
	public void dictAddUpdate(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("dictAddandUpdate");
		String id = request.getParameter("id");
		String nameZh = request.getParameter("nameZh");
		String nameEn = request.getParameter("nameEn");
		int dictType = Integer.parseInt(request.getParameter("dictType"));
		int sort = Integer.parseInt(request.getParameter("sort").trim());
		User user = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		Dict dict = new Dict();
		dict.setNameZh(nameZh);
		dict.setNameEn(nameEn);
		dict.setDictType(dictType);
		dict.setSort(sort);
		Dict d2 = new Dict();
		if (!id.equals("0") && !id.equals("0") && id != null) {
			dict.setId(Integer.parseInt(id));
			Dict logDict = publicService.findDict(Integer.parseInt(id));
			int logTime = 0;
			try {
				d2 = baseService.editDict(dict);
			} catch (Exception e) {
				this.Log(
						user.getId(),
						"general_data",
						null,
						null,
						"【" + user.getNickname() + "】【修改】字典【"
								+ logDict.getNameZh() + "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(
						user.getId(),
						"general_data",
						null,
						null,
						"【" + user.getNickname() + "】【修改】字典【"
								+ logDict.getNameZh() + "】成功！修改为【" + nameZh
								+ "】", 0);
			}

		} else if (id.equals("0")) {
			int logTime = 0;
			try {
				d2 = baseService.saveDict(dict);
			} catch (Exception e) {
				this.Log(user.getId(), "general_data", null, null,
						"【" + user.getNickname() + "】【新增】字典【" + nameZh
								+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(
						user.getId(),
						"general_data",
						null,
						null,
						"【" + user.getNickname() + "】【新增】字典【" + nameZh + "】成功！",
						0);
			}

		}
		String result = formatToJson(d2);
		// System.out.println("resultadd    Dict 插入  更新：" + result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 获取更新内容 显示到 dict_add_update.html 网页
	@RequestMapping("dictfindone")
	public void toDictFindOne(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		HashMap<String, Object> dictMap = new HashMap<String, Object>();
		Dict dict = publicService.findDict(Integer.parseInt(id));
		if (dict != null) {
			dictMap.put("nameZh", dict.getNameZh());
			dictMap.put("nameEn", dict.getNameEn());
			dictMap.put("dictType", dict.getDictType());
			dictMap.put("sort", dict.getSort());
		}
		String result = formatToJson(dictMap);
		// System.out.println("result  dict 获取更新内容:"+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	/**
	 * 字典项管理
	 */
	// 字典项表结构查询
	@RequestMapping("findallDictItemBiao")
	@ResponseBody
	public void findAllDictItemBiao(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("findallDictItem(biao)");
		Integer dictId = Integer.parseInt(request.getParameter("dictId"));
		Integer pageNumber = 15;
		Integer pageSize = Integer.parseInt(request.getParameter("page"));
		String queryParam = request.getParameter("queryParams");
		String text = request.getParameter("text");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if (text != null && !"".equals(text)) {
			queryParams.put("%," + queryParam, text);
		}
		if (dictId != null && !"".equals(dictId)) {
			queryParams.put("=,dictId", dictId);
		}
		Integer count = publicService.getDictItemCount(queryParams);
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		List<DictItem> list = publicService.getDictItem(queryParams, pageSize,
				pageNumber);
		for (int i = 0; i < list.size(); i++) {
			DictItem dictItem = list.get(i);
			if (dictItem != null) {
				mp = new LinkedHashMap<String, Object>();
				mp.put("id", dictItem.getId());
				mp.put("nameZh", dictItem.getNameZh());
				mp.put("nameEn", dictItem.getNameEn());
				mp.put("value", dictItem.getValue());
				mp.put("sort", dictItem.getSort());
				mp.put("dictId", dictItem.getDictId());
				if (dictItem.getDictItemId() != null
						&& 0 != dictItem.getDictItemId()) {
					DictItem d = publicService.findDictItem(dictItem
							.getDictItemId());
					mp.put("Iid", d.getId());
					mp.put("IdictItem", d.getNameZh());
				} else {
					mp.put("Iid", "0");
				}
				r.add(mp);
			}
		}
		String result = formatToJson(r);
		// System.out.println("result DictItem  :" + result);
		StringBuffer sb = new StringBuffer();
		sb.append("{\"listsize\":" + list.size() + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 字典项 zTree结构查询
	@RequestMapping("findallDictItemZTree")
	@ResponseBody
	public void findAllDictItemZTree(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("findAllDictItemZTree(zTree)");
		String dictId = request.getParameter("dictId");
//		String id = request.getParameter("id");
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		Dict dict = publicService.findDict(Integer.parseInt(dictId));
		List<DictItem> list = publicService.getDictItem(dict);
		for (int i = 0; i < list.size(); i++) {
			DictItem dictItem = list.get(i);
			mp = new LinkedHashMap<String, Object>();
			mp.put("id", dictItem.getId());
			mp.put("name", dictItem.getNameZh()); // 及 nameZh 中文名称
			mp.put("nameEn", dictItem.getNameEn());
			mp.put("value", dictItem.getValue());
			mp.put("sort", dictItem.getSort());
			mp.put("dictId", dictItem.getDictId());
			if (dictItem.getDictItemId() != null
					&& dictItem.getDictItemId() != 0) {
				DictItem d = publicService.findDictItem(dictItem
						.getDictItemId());
				mp.put("pId", d.getId());
			} else {
				mp.put("pId", "0");
			}
			r.add(mp);
		}
		String result = formatToJson(r);
		// System.out.println("result DictItem 【zTree】  :" + result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 字典项导出Excel
	@RequestMapping("exportExcelDict")
	public void exportExcelDict(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		String id = request.getParameter("id");
		String path =  XxlConfClient.get("dal.file.path", "") +"/";
		Dict dict = publicService.findDict(Integer.parseInt(id));
		List<HashMap<String, Object>> listDictItemData = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> mapdict = new HashMap<String, Object>();
		mapdict.put("id", dict.getId());
		mapdict.put("nameEn",dict.getNameEn());
		mapdict.put("nameZh",dict.getNameZh());
		mapdict.put("type",dict.getDictType());
		mapdict.put("sort",dict.getSort());
		listDictItemData.add(mapdict);
		List<DictItem> dictItemList = publicService.getDictItem(dict);
		List<HashMap<String, Object>> listData = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> map = null;
		for (int i = 0; i < dictItemList.size(); i++) {
			DictItem dictItem = dictItemList.get(i);
			map = new HashMap<String, Object>();
			map.put("id", dictItem.getId());
			map.put("nameEn", (null != dictItem.getNameEn()) ? dictItem.getNameEn() : "");
			map.put("nameZh", (null != dictItem.getNameZh() ) ? dictItem.getNameZh() : "");
			map.put("value",  (null != dictItem.getValue() ) ? dictItem.getValue() : "");
			map.put("dictId", (null != dictItem.getDictId() ) ? dictItem.getDictId() : "");
			if(null != dictItem.getDictItemId() && !"".equals(dictItem.getDictItemId()) && 0 != dictItem.getDictItemId()){
				DictItem upDictItem = publicService.findDictItem(dictItem.getDictItemId());
				map.put("dictItemName", (null != upDictItem.getNameEn() ) ? upDictItem.getNameEn() : "");
			}else{
				map.put("dictItemName","");
			}
			
			map.put("sort", (null != dictItem.getSort() ) ? dictItem.getSort() : "");
			map.put("level", (null != dictItem.getLevel() ) ? dictItem.getLevel() : "");
			listData.add(map);
		}
		HashMap<String, List<HashMap<String, Object>>> excelMap = new HashMap<String, List<HashMap<String, Object>>>();
		excelMap.put("字典", listDictItemData);
		excelMap.put("字典项", listData);
		DBUtils.writeExcelList(path + dict.getNameEn() + ".xls", excelMap, 1);
		downloadkk(request, response, dict.getNameEn() + ".xls", path);
	}
	// 字典项导出XML
	@RequestMapping("exportDict")
	public void toDictItemExportList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		Dict dictList = publicService.findDict(Integer.parseInt(id));
		DocumentBuilderFactory fct = DocumentBuilderFactory.newInstance();
		DocumentBuilder bui;
		try {
			// 驱动
			bui = fct.newDocumentBuilder();
			// 创建对象
			Document doc = bui.newDocument();
			// 设置根目录
			Element dict_data = doc.createElement("dict_data");


			// 设置二级目录
			Element dict = doc.createElement("dict");

			// 二级标题属性
			Attr type = doc.createAttribute("type");
			// 赋值
			type.setNodeValue(dictList.getDictType().toString());
			// 写入二级目录
			dict.setAttributeNode(type);
			// 二级标题属性
			Attr dictId = doc.createAttribute("id");
			// 赋值
			dictId.setNodeValue(dictList.getId().toString());
			// 写入二级目录
			dict.setAttributeNode(dictId);
			Attr title = doc.createAttribute("title");
			if (dictList.getDictType() == 1) {
				title.setNodeValue("普通结构(名称-值)");
			} else {
				title.setNodeValue("树形结构");
			}
			dict.setAttributeNode(title);

			// 创建节点
			Element name_zh = doc.createElement("name_zh");
			// 赋值
			name_zh.setTextContent(dictList.getNameZh());

			Element name_en = doc.createElement("name_en");
			name_en.setTextContent(dictList.getNameEn());

			Element sort = doc.createElement("sort");
			sort.setTextContent(dictList.getSort().toString());

			// 将节点写入二级目录
			dict.appendChild(name_zh);
			dict.appendChild(name_en);
			dict.appendChild(sort);

			// 创建三级目录
			Element dict_item_data = doc.createElement("dict_item_data");

			List<DictItem> list = publicService.getDictItem(dictList);
			for (DictItem dictItem : list) {
				if (dictList.getDictType() == 1) {
					// 创建四级目录
					Element dict_item = doc.createElement("dict_item");

					// 属性
					Attr id1 = doc.createAttribute("id");
					id1.setNodeValue(dictItem.getId().toString());
					dict_item.setAttributeNode(id1);

					// 节点
					Element di_name_zh = doc.createElement("name_zh");
					di_name_zh.setTextContent(dictItem.getNameZh());

					Element di_name_en = doc.createElement("name_en");
					di_name_en.setTextContent(dictItem.getNameEn());

					Element di_value = doc.createElement("value");
					di_value.setTextContent(dictItem.getValue());

					Element di_sort = doc.createElement("sort");
					di_sort.setTextContent(dictItem.getSort().toString());
					

					// 赋值
					dict_item.appendChild(di_name_zh);
					dict_item.appendChild(di_name_en);
					dict_item.appendChild(di_value);
					dict_item.appendChild(di_sort);
					if(null != dictItem.getLevel() && !"".equals(dictItem.getLevel())){
						Element di_level = doc.createElement("level");
						di_level.setTextContent(dictItem.getLevel().toString());
						dict_item.appendChild(di_level);
					}

					// 写入上级目录
					dict_item_data.appendChild(dict_item);

				} else {
					// Element
					// dict_item_data=doc.createElement("dict_item_data");
					Element dict_item = doc.createElement("dict_item");

					Attr id1 = doc.createAttribute("id");
					id1.setNodeValue(dictItem.getId().toString());
					dict_item.setAttributeNode(id1);

					Element di_name_zh = doc.createElement("name_zh");
					di_name_zh.setTextContent(dictItem.getNameZh());

					Element di_name_en = doc.createElement("name_en");
					di_name_en.setTextContent(dictItem.getNameEn());

					Element di_value = doc.createElement("value");
					di_value.setTextContent(dictItem.getValue());

					Element di_dict_item_nameen = doc.createElement("dict_item_nameen");
					if (dictItem.getDictItemId() != null && !"".equals(dictItem.getDictItemId())) {
						DictItem upDictItem = publicService.findDictItem(dictItem.getDictItemId());
						di_dict_item_nameen.setTextContent(upDictItem.getNameEn());
					}

					Element di_sort = doc.createElement("sort");
					di_sort.setTextContent(dictItem.getSort().toString());

					
					dict_item.appendChild(di_name_zh);
					dict_item.appendChild(di_name_en);
					dict_item.appendChild(di_value);
					dict_item.appendChild(di_sort);
					if (dictItem.getDictItemId() != null && !"".equals(dictItem.getDictItemId())) {
						dict_item.appendChild(di_dict_item_nameen);
					}
					if(null != dictItem.getLevel() && !"".equals(dictItem.getLevel())){
						Element di_level = doc.createElement("level");
						di_level.setTextContent(dictItem.getLevel().toString());
						dict_item.appendChild(di_level);
					}
					dict_item_data.appendChild(dict_item);
					
					// dict.appendChild(dict_item_data);
				}

			}
			// 写入上级目录
			dict.appendChild(dict_item_data);
			// 写入上级目录
			dict_data.appendChild(dict);

			// 目录保存到doc
			doc.appendChild(dict_data);

			// step9:获得一个TransformerFactory对象
			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
			// step10:获得一个Transformer对象
			Transformer transformer = transformerFactory.newTransformer();
			// step11:把document对象用一个DOMSource对象包装起来
			Source xmlSource = new DOMSource(doc);
			// step12:建立一个存储目标对象
			// 获取服务器地址
			ServletContext sc = request.getSession().getServletContext();
			String dir = sc.getRealPath("/XMLFile/");
			File dirFile = new File(dir);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			String random = System.nanoTime() + ".xml";
			File downFile = new File(dirFile, random);
			Result outputTarget = new StreamResult(downFile);
			// step13:生成相应的xml文件
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty(
					"{http://xml.apache.org/xslt}indent-amount", "4");
			transformer.transform(xmlSource, outputTarget);

			// 下载文件
			FileDownloadUtil.download(downFile, dictList.getNameZh()+".xml", request, response);

		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	//导入
	@RequestMapping("importDict")
	public void importDict(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String urlFile = request.getParameter("urlFile");
		//访问前缀	
		String uploadPath =  XxlConfClient.get("dal.file.server", "") +"/";
		//磁盘前缀
		String adjunctPath =  XxlConfClient.get("dal.file.path", "");
		LinkedHashMap<String, Object> r = new LinkedHashMap<String, Object>();
		
		urlFile = urlFile.replaceAll(uploadPath, "");
		String lastType = urlFile.substring(urlFile.lastIndexOf(".")+1, urlFile.length());
		try {
			if("xml".equals(lastType)){
				String rXml = this.importDictXml(adjunctPath+"/"+urlFile);
				r.put("data", rXml);
			}else if("xls".equals(lastType) || "xlsx".equals(lastType)){
				String rExcel = this.importDictExcel(adjunctPath+"/"+urlFile);
				r.put("data", rExcel);
			}else{
				r.put("data", "type");
			}
		} catch (Exception e) {
			r.put("data", "no");
		}
		
		String result = formatToJson(r);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	//字典导入Excel
	public String importDictExcel(String path) throws Exception{
		HashMap<String, List<HashMap<String, Object>>> data = DBUtils.readExcelAll(path);
		Dict aDict = null;
		String r = "yes";
		try {
			for (int i = 0; i < data.get("字典").size(); i++) {
				HashMap<String, Object> dictMap = data.get("字典").get(i);
				Dict dict = new Dict();
				dict.setNameEn(dictMap.get("nameEn").toString());
				dict.setNameZh(dictMap.get("nameZh").toString());
				dict.setDictType(Integer.parseInt(dictMap.get("type").toString()));
				dict.setSort(Integer.parseInt(dictMap.get("sort").toString()));
				aDict = baseService.saveDict(dict);
			}
			HashMap<String, Object> queryParams = null;
			for (int i = 0; i < data.get("字典项").size(); i++) {
				HashMap<String, Object> dictItemMap = data.get("字典项").get(i);
				DictItem dictItem = new DictItem();
				dictItem.setNameEn(dictItemMap.get("nameEn").toString());
				dictItem.setNameZh(dictItemMap.get("nameZh").toString());
				dictItem.setValue(dictItemMap.get("value").toString());
				dictItem.setDictId(aDict.getId());
				if(null != dictItemMap.get("dictItemName") && !"".equals(dictItemMap.get("dictItemName"))){
					queryParams = new HashMap<String, Object>();
					queryParams.put("=,dict_id", aDict.getId());
					queryParams.put("=,name_en", dictItemMap.get("dictItemName"));
					List<DictItem> dictItemList = publicService.getDictItem(queryParams, 1, 1);
					if(null != dictItemList && dictItemList.size()>0 ){
						dictItem.setDictItemId(dictItemList.get(0).getId());
					}
				}
				dictItem.setSort(Integer.parseInt(dictItemMap.get("sort").toString()));
				if(null != dictItemMap.get("level") && !"".equals(dictItemMap.get("level"))){
					dictItem.setLevel(Integer.parseInt(dictItemMap.get("level").toString()));
				}
				baseService.saveDictItem(dictItem);
			}
		} catch (Exception e) {
			r = "no";
		}
		return r;
	}
	public String importDictXml(String path) throws Exception{
		String r = "yes";
		// 解析文件，生成document对象
		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document document = builder.parse(new File(path));
			// 生成XPath对象
			XPath xpath = XPathFactory.newInstance().newXPath();
			// 获取节点集合
			NodeList dictXml = (NodeList) xpath.evaluate("//dict",document, XPathConstants.NODESET);
			for (int i = 0; i < dictXml.getLength(); i++) {
				Node dictData = dictXml.item(i);
				// 属性id
				String dictType = xpath.evaluate("@type", dictData,XPathConstants.STRING).toString();

				// 一级所有值
				String dictNameZh = xpath.evaluate("name_zh", dictData,XPathConstants.STRING).toString();
				String dictNameEn = xpath.evaluate("name_en", dictData,XPathConstants.STRING).toString();
				String dictSort = xpath.evaluate("sort", dictData,XPathConstants.STRING).toString();
				Dict dict = new Dict();
				dict.setNameEn(dictNameEn);
				dict.setNameZh(dictNameZh);
				dict.setDictType(Integer.parseInt(dictType));
				dict.setSort(Integer.parseInt(dictSort));
				Dict aDict = baseService.saveDict(dict);
				// 二级节点内容
				HashMap<String, Object> queryParams = null;
				NodeList dictItemDataNode = (NodeList) xpath.evaluate("//dict_item", document, XPathConstants.NODESET);
				for (int j = 0; j < dictItemDataNode.getLength(); j++) {
					Node dictItemData = dictItemDataNode.item(j);
					// 二级节点所以值
					String dictItemNameZh = xpath.evaluate("name_zh", dictItemData,XPathConstants.STRING).toString();
					String dictItemNameEn = xpath.evaluate("name_en", dictItemData,XPathConstants.STRING).toString();
					String value = xpath.evaluate("value", dictItemData,XPathConstants.STRING).toString();
					Object dictItemUpNameEn = xpath.evaluate("dict_item_nameen", dictItemData,XPathConstants.STRING);
					String dictItemSort = xpath.evaluate("sort", dictItemData,XPathConstants.STRING).toString();
					Object level = xpath.evaluate("level", dictItemData,XPathConstants.STRING);
					DictItem dictItem = new DictItem();
					dictItem.setNameEn(dictItemNameEn);
					dictItem.setNameZh(dictItemNameZh);
					dictItem.setValue(value);
					dictItem.setDictId(aDict.getId());
					if(null != dictItemUpNameEn && !"".equals(dictItemUpNameEn)){
						queryParams = new HashMap<String, Object>();
						queryParams.put("=,dict_id", aDict.getId());
						queryParams.put("=,name_en", dictItemUpNameEn);
						List<DictItem> dictItemList = publicService.getDictItem(queryParams, 1, 1);
						if(null != dictItemList && dictItemList.size()>0 ){
							dictItem.setDictItemId(dictItemList.get(0).getId());
						}
					}
					dictItem.setSort(Integer.parseInt(dictItemSort));
					if(null != level && !"".equals(level)){
						dictItem.setLevel(Integer.parseInt(level.toString()));
					}
					baseService.saveDictItem(dictItem);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return r;
	}
	@RequestMapping("dictItemExportList")
	public void download(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// toDictItemExportList();
		String fileName = "persons" + ".xml";
		String path =XxlConfClient.get("dal.file.path", "");//"D://"
		downloadkk(request, response, fileName, path);

	}

	public void downloadkk(HttpServletRequest request,
			HttpServletResponse response, String fileName, String path)
			throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName="
				+ fileName);
		try {
			// 这个download目录为啥建立在classes下的
			InputStream inputStream = new FileInputStream(new File(path + "/"
					+ File.separator + fileName));
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			// 这里主要关闭。
			os.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	
	
	// 插入 更新 字典项 数据
	@RequestMapping("dictItemAddandUpdate")
	@ResponseBody
	public void dictItemAddUpdate(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("dictItemAddUpdate()  字典项  插入 更新");
		String id = request.getParameter("id"); // 新建id
		String nameZh = request.getParameter("nameZh");
		String nameEn = request.getParameter("nameEn");
		String value = request.getParameter("value");
		int sort = Integer.parseInt(request.getParameter("sort"));
		User user = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		String dictId = request.getParameter("dictId"); // 所属字典类 id
		String dictItemId = request.getParameter("dictItemId");
		DictItem dictItme = new DictItem();
		dictItme.setNameZh(nameZh);
		dictItme.setNameEn(nameEn);
		dictItme.setValue(value);
		dictItme.setSort(sort);
		if (dictId != null && dictId != "" && !dictId.equals("0")) {
			dictItme.setDictId(Integer.parseInt(dictId));
		}
		// 判断 是否有 父类
		if (dictItemId != null && dictItemId != "") {
			dictItme.setDictItemId(Integer.parseInt(dictItemId));
			if(Integer.parseInt(dictItemId) != 0){
				DictItem dictItem = publicService.findDictItem(Integer.parseInt(dictItemId));
				dictItme.setLevel(dictItem.getLevel()+1);
			}else{
				dictItme.setLevel(1);
			}
		}else{
			dictItme.setLevel(1);
		}
		// 判断 是 新增 还是 更新
		DictItem d2 = new DictItem();
		if (id != null && id != "" && !id.equals("0")) {
			dictItme.setId(Integer.parseInt(id));
			DictItem dictItem = publicService
					.findDictItem(Integer.parseInt(id));
			int logTime = 0;
			try {
				d2 = baseService.editDictItem(dictItme);
			} catch (Exception e) {
				this.Log(
						user.getId(),
						"general_data",
						null,
						null,
						"【" + user.getNickname() + "】【修改】字典项【"
								+ dictItem.getNameZh() + "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(
						user.getId(),
						"general_data",
						null,
						null,
						"【" + user.getNickname() + "】【修改】字典项【"
								+ dictItem.getNameZh() + "】成功！修改为【" + nameZh
								+ "】", 0);
			}

		} else {
			int logTime = 0;
			try {
				d2 = baseService.saveDictItem(dictItme);
			} catch (Exception e) {
				this.Log(user.getId(), "general_data", null, null,
						"【" + user.getNickname() + "】【新增】字典项【" + nameZh
								+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(user.getId(), "general_data", null, null,
						"【" + user.getNickname() + "】【新增】字典项【" + nameZh
								+ "】成功！", 0);
			}

		}
		LinkedHashMap<String, Object> r = new LinkedHashMap<String, Object>();
		r.put("dictId", d2.getDictId());
		r.put("dictItemId", d2.getDictItemId());
		r.put("id", d2.getId());
		r.put("level", d2.getLevel());
		r.put("nameEn", d2.getNameEn());
		r.put("nameZh", d2.getNameZh());
		r.put("sort", d2.getSort());
		r.put("value", d2.getValue());
		r.put("name", d2.getNameZh());
		String result = formatToJson(r);
		// System.out.println("resultadd    DictItme 插入  更新：" + result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	
	//自动字典项值
	@RequestMapping("dictValue")
	public void dictValue(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String dictId = request.getParameter("dictId");
		String dictItemId = request.getParameter("dictItemId");
		String rValue="";
		int rSort=1;
		HashMap<String, Object> r = new HashMap<String, Object>();
		HashMap<String, Object> dictItemParams = null;
		List<String> valueList  = null;
		List<Integer> solrList  = null;
		if("0".equals(dictItemId)){
			dictItemParams = new LinkedHashMap<String, Object>();
			dictItemParams.put("=,dict_id", dictId);
			List<DictItem> dictItemList = publicService.getDictItem(dictItemParams, 1, publicService.getDictItemCount(dictItemParams));
			if(dictItemList != null && dictItemList.size()>0){
				valueList = new ArrayList<String>();
				solrList = new ArrayList<Integer>();
				for (int i = 0; i < dictItemList.size(); i++) {
					DictItem dictItem = dictItemList.get(i);
					String values = dictItem.getValue();
					String value = values.substring(1, values.length());
					boolean isNum = value.matches("^\\d+$");
					if(isNum){
						valueList.add(value);
					}
					solrList.add(dictItem.getSort());
				}
				if(valueList != null && valueList.size()>0){
					String maxValue = Collections.max(valueList);
					int intmaxValue = Integer.parseInt(maxValue);
					if(intmaxValue<10){
					    if(intmaxValue+1 == 10){
	                        rValue = "A"+(intmaxValue+1);
	                    }else{
	                        rValue = "A0"+(intmaxValue+1);
	                    }
					}else{
						rValue = "A"+(intmaxValue+1);
					}
				}else{
					rValue = "A01";
				}
				if(solrList != null && solrList.size()>0){
					int maxValue = Collections.max(solrList);
					rSort = maxValue+1;
				}
			}else{
				rValue = "A01";
			}
		}else{
			if(dictItemId != null && !"".equals(dictItemId)){
				DictItem aDictItem = publicService.findDictItem(Integer.parseInt(dictItemId));
				int count = aDictItem.getLevel()+1;
				String key = Letter.getLetter(count);
				dictItemParams = new LinkedHashMap<String, Object>();
				dictItemParams.put("=,dict_item_id", dictItemId);
				List<DictItem> dictItemList = publicService.getDictItem(dictItemParams, 1, publicService.getDictItemCount(dictItemParams));
				if(dictItemList != null && dictItemList.size()>0){
					valueList = new ArrayList<String>();
					solrList = new ArrayList<Integer>();
					for (int i = 0; i < dictItemList.size(); i++) {
						DictItem dictItem = dictItemList.get(i);
						String values = dictItem.getValue();
						String [] aValue = values.split("\\.");
						values = aValue[aValue.length-1];
						String value = values.substring(1, values.length());
						boolean isNum = value.matches("^\\d+$");
						if(isNum){
							valueList.add(value);
						}
						solrList.add(dictItem.getSort());
					}
					if(valueList != null && valueList.size()>0){
						String maxValue = Collections.max(valueList);
						int intmaxValue = Integer.parseInt(maxValue);
						if(intmaxValue<10){
							rValue = aDictItem.getValue()+"."+key+"0"+(intmaxValue+1);
						}else{
							rValue = aDictItem.getValue()+"."+key+(intmaxValue+1);
						}
					}else{
						rValue = aDictItem.getValue()+"."+key+"01";
					}
					if(solrList != null && solrList.size()>0){
						int maxValue = Collections.max(solrList);
						rSort = maxValue+1;
					}
				}else{
					rValue = aDictItem.getValue()+"."+key+"01";
				}
			}else{
				dictItemParams = new LinkedHashMap<String, Object>();
				dictItemParams.put("=,dict_id", dictId);
				dictItemParams.put("=,level", 1);
				List<DictItem> dictItemList = publicService.getDictItem(dictItemParams, 1, publicService.getDictItemCount(dictItemParams));
				if(dictItemList != null && dictItemList.size()>0){
					valueList = new ArrayList<String>();
					solrList = new ArrayList<Integer>();
					for (int i = 0; i < dictItemList.size(); i++) {
						DictItem dictItem = dictItemList.get(i);
						String values = dictItem.getValue();
						String value = values.substring(1, values.length());
						boolean isNum = value.matches("^\\d+$");
						if(isNum){
							valueList.add(value);
						}
						solrList.add(dictItem.getSort());
					}
					if(valueList != null && valueList.size()>0){
						String maxValue = Collections.max(valueList);
						int intmaxValue = Integer.parseInt(maxValue);
						if(intmaxValue<10){
						    if(intmaxValue+1 == 10){
	                            rValue = "A"+(intmaxValue+1);
	                        }else{
	                            rValue = "A0"+(intmaxValue+1);
	                        }
						}else{
							rValue = "A"+(intmaxValue+1);
						}
					}else{
						rValue = "A01";
					}
					if(solrList != null && solrList.size()>0){
						int maxValue = Collections.max(solrList);
						rSort = maxValue+1;
					}
				}else{
					rValue = "A01";
				}
			}
			
		}
		r.put("value", rValue);
		r.put("sort", rSort);
		String result = formatToJson(r);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 获取dictItem更新内容 显示到 dictItem_add_update.html 网页
	@RequestMapping("dictItmefindone")
	public void toDictItmeFindOne(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer id = Integer.parseInt(request.getParameter("id").trim());
		HashMap<String, Object> dictItemMap = new HashMap<String, Object>();
		DictItem dictitem = publicService.findDictItem(id);
		if (dictitem != null) {
			dictItemMap.put("id", dictitem.getId());
			dictItemMap.put("nameZh", dictitem.getNameZh());
			dictItemMap.put("nameEn", dictitem.getNameEn());
			dictItemMap.put("value", dictitem.getValue());
			dictItemMap.put("sort", dictitem.getSort());
			if (dictitem.getDictItemId() != null
					&& dictitem.getDictItemId() != 0) {
				DictItem d = publicService.findDictItem(dictitem
						.getDictItemId());
				dictItemMap.put("dictitemName", d.getNameZh());
				dictItemMap.put("dictitemId", d.getId());
			}
		}
		String result = formatToJson(dictItemMap);
		// System.out.println("result  dictitem 获取更新内容:"+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 删除字典项单条数据
	@RequestMapping("deldictiem")
	public void toDictiemDelOne(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("delete");
		Integer id = Integer.parseInt(request.getParameter("id"));
		DictItem dictitem = publicService.findDictItem(id);
		//List<Classes> listClasses = publicService.getClasses();
		boolean falg = false;
		/*for (Classes classes : listClasses) {
			List<DataProperty> aDataPropertyList = publicService
					.getDataProperty(classes);
			for (int i = 0; i < aDataPropertyList.size(); i++) {
				DataProperty aDataProperty = aDataPropertyList.get(i);
				if (aDataProperty.getDictId() == dictitem.getDictId()) {
					long dynamicCount = dynamicService.getDynamicCount(
							classes.getNameEn(), null);
					int kk = (int) dynamicCount;
					List<Map<String, Object>> aDynamicData = dynamicService
							.getDynamicData(classes.getNameEn(), null, 1, kk);
					for (int j = 0; j < aDynamicData.size(); j++) {
						String ll = (String) aDynamicData.get(j).get(
								aDataProperty.getNameEn());
						// System.out.println(ll);
						if (ll != null && ll.equals(dictitem.getValue())) {
							falg = true;
						}
					}
				}
			}
		}*/
		int size = 0;
		if (falg == false) {
			int logTime = 0;
			User user = publicService.findUser((Integer) request.getSession()
					.getAttribute("userid"));
			try {
				baseService.deleteDictItem(dictitem);
			} catch (Exception e) {
				this.Log(
						user.getId(),
						"general_data",
						null,
						null,
						"【" + user.getNickname() + "】【删除】字典项【"
								+ dictitem.getNameZh() + "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(
						user.getId(),
						"general_data",
						null,
						null,
						"【" + user.getNickname() + "】【删除】字典项【"
								+ dictitem.getNameZh() + "】成功！", 0);
			}

			size = 1;
		}
		String result = "{\"count\":" + size + "}";
		// System.out.println("reult dict 删除字典项单条数据: "+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	// 删除字典项全部
	@RequestMapping("deldictiemAll")
	public void deldictiemAll(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int size = 1;
		Integer id;
		try {
			id = Integer.parseInt(request.getParameter("id"));
			HashMap<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("=,dict_id", id);
			List<DictItem> dictItemList = publicService.getDictItem(queryParams, 1, publicService.getDictItemCount(queryParams));
			for (int i = 0; i < dictItemList.size(); i++) {
				DictItem dictItem = dictItemList.get(i);
				baseService.deleteDictItem(dictItem);
			}
		} catch (Exception e) {
			id=0;
			e.printStackTrace();
		}
		String result = "{\"count\":" + size + "}";
		// System.out.println("reult dict 删除字典项单条数据: "+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 用户登录 页面
	@RequestMapping("userlogin")
	public void toUserlogin(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String username = request.getParameter("username");
		String kaptcha = request.getParameter("kaptcha");
		String password = MD5.convert(request.getParameter("password"));
		
		Cookie cookie = new Cookie("ticket",MD5.string2MD5(username+"∷"+password));
        cookie.setMaxAge(60*60*24*180);// 设置为180day
        cookie.setPath("/");
        cookie.setDomain(request.getServerName());
        response.addCookie(cookie);
        
        Cookie cookieUserName = new Cookie("ticketUserName",username);
        cookieUserName.setMaxAge(60*60*24*180);// 设置为180day
        cookieUserName.setPath("/");
        cookieUserName.setDomain(request.getServerName());
        response.addCookie(cookieUserName);
		HashMap<String, Object> user = new HashMap<String, Object>();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.CHINA);
		Date stipulateTime = sdf.parse("2018/2/28");
		Date nowTime = new Date();

		// if(stipulateTime.after(nowTime)){
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("=,username", username);
		queryParams.put("=,password", password);
		List<User> users = publicService.getUser(queryParams, 1, 1);

		HttpSession session = request.getSession();
		String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		boolean kaptchaBoolean = false;
		boolean pad = false;
		int count = 0;
		Object sessionOne = request.getSession().getAttribute("kaptchaTime");
		if (sessionOne != null) {
			count = Integer.parseInt(String.valueOf(sessionOne));
		} else {
			request.getSession().setAttribute("kaptchaTime", 0);
		}
		if (count <= 2) {
			pad = true;
		}
		// 判断为NULL 或者“” StringUtils.isBlank(kaptcha)
		if (kaptcha.equals(code) || pad == true) {
			if (users.size() > 0) {
				for (int i = 0; i < users.size(); i++) {
					User u = users.get(i);
					user.put("username", u.getNickname());
					user.put("userid", u.getId());
					request.getSession().setAttribute("username",
							u.getNickname());
					request.getSession()
							.setAttribute("userkk", u.getNickname());
					request.getSession().setAttribute("userid", u.getId());
					request.getSession().setAttribute("departmentid",
							u.getDepartmentId());
					user.put("tishi", "ok");
					kaptchaBoolean = true;
					request.getSession().setAttribute("kaptchaTime", 0);
					this.Log(u.getId(), "login", null, null,
							"【" + u.getUsername() + "】登陆成功！", 0);
					break;
				}
			} else {
				user.put("tishi", "no");
				this.Log(0, "login", null, null, "【" + username
						+ "】登陆失败，用户名或者密码错误！", 1);
			}
		} else {
			user.put("tishi", "kaptcha");
		}
		if (kaptchaBoolean == false) {
			count = count + 1;
			request.getSession().setAttribute("kaptchaTime", count);
			user.put("kaptchaTime", count);
		}
		/*
		 * }else{ user.put("tishi", "pastTime"); }
		 */
		String result = formatToJson(user);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 配置 layout.html 用户权限
	@RequestMapping("loginLayout")
	public void tologinLayout(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// response.sendRedirect("login.html");
		User u = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		request.getSession().setAttribute("username", null);
		request.getSession().setAttribute("userid", null);
		request.getSession().setAttribute("departmentid", null);
		HashMap<String, Object> user = new HashMap<String, Object>();
		user.put("tishi", "ok");
		this.Log(u.getId(), "logout", null, null, "【" + u.getUsername()
				+ "】安全退出！", 0);
		String result = formatToJson(user);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	/**
	 * 数据源管理
	 */
	// 数据源查询
	@RequestMapping("findallDataSource")
	@ResponseBody
	public void tofindAllDataSource(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("findallDataSource");
		Integer pageNumber = Integer.parseInt(request
				.getParameter("pageNumber"));
		Integer pageSize = 1;
		if (request.getParameter("page") != null) {
			pageSize = Integer.parseInt(request.getParameter("page"));
		} else {
			pageSize = 1;
		}
		String queryParam = request.getParameter("queryParams");

		String text = request.getParameter("text");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if (text != null && !"".equals(text)) {
			queryParams.put("%," + queryParam, text);
		}
		Integer count = publicService.getDataSourceCount(queryParams);
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		List<DataSource> list = publicService.getDataSource(queryParams,
				pageSize, pageNumber);
		for (int i = 0; i < list.size(); i++) {
			DataSource dataSource = list.get(i);
			if (dataSource != null) {
				mp = new LinkedHashMap<String, Object>();
				mp.put("id", dataSource.getId());
				mp.put("name", dataSource.getName());
				mp.put("description", dataSource.getDescription());
				mp.put("sourceType", dataSource.getSourceType());
				mp.put("url", dataSource.getUrl());
				mp.put("user", dataSource.getUser());
				mp.put("password", dataSource.getPassword());
				if (dataSource.getStatus() == 1) {
					mp.put("classYangShi", "label-success");
					mp.put("status", "可使用");
				} else if (dataSource.getStatus() == 2) {
					mp.put("classYangShi", "btn-danger");
					mp.put("status", "禁 &nbsp;&nbsp;用 ");
				}
				r.add(mp);
			}
		}
		String result = formatToJson(r);
		// System.out.println("result:" +result);
		StringBuffer sb = new StringBuffer();
		int listsize = list.size();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 插入 更新 数据源 数据
	@RequestMapping("addEditDataSource")
	@ResponseBody
	public void toaddEditDataSource(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("addEditDataSource");
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String description = request.getParameter("description");
		String sourceType = request.getParameter("sourceType");
		String url = request.getParameter("url");
		String user = request.getParameter("user");
		String password = request.getParameter("password");
		int status = Integer.parseInt(request.getParameter("status"));
		User logUser = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		DataSource dataSource = new DataSource();
		dataSource.setName(name);
		dataSource.setDescription(description);
		dataSource.setSourceType(sourceType);
		dataSource.setUrl(url);
		dataSource.setUser(user);
		dataSource.setPassword(password);
		dataSource.setStatus(status);
		DataSource d2 = new DataSource();
		if (!id.equals("0") && !id.equals("0") && id != null) {
			dataSource.setId(Integer.parseInt(id));
			DataSource logDataSource = publicService.findDataSource(Integer
					.parseInt(id));
			int logTime = 0;
			try {
				d2 = baseService.editDataSource(dataSource);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null,
						"【" + logUser.getNickname() + "】【修改】数据源【"
								+ logDataSource.getName() + "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null,
						"【" + logUser.getNickname() + "】【修改】数据源【"
								+ logDataSource.getName() + "】成功！修改为【" + name
								+ "】", 0);
			}

		} else if (id.equals("0")) {
			int logTime = 0;
			try {
				d2 = baseService.saveDataSource(dataSource);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】数据源【" + name
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】数据源【" + name + "】成功！",
						0);
			}

		}
		String result = formatToJson(d2);
		// System.out.println("resultadd    Dict 插入  更新：" + result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 获取数据源更新内容
	@RequestMapping("dataSourceEditShow")
	public void toDataSourceEditShow(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("dataSourceEditShow 更新");
		Integer id = Integer.parseInt(request.getParameter("id"));
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		DataSource dataSource = publicService.findDataSource(id);
		if (dataSource != null) {
			dMap.put("id", dataSource.getId());
			dMap.put("name", dataSource.getName());
			dMap.put("description", dataSource.getDescription());
			dMap.put("sourceType", dataSource.getSourceType());
			dMap.put("user", dataSource.getUser());
			dMap.put("password", dataSource.getPassword());
			dMap.put("status", dataSource.getStatus());
		}
		String result = formatToJson(dMap);
		// System.out.println("result  dictitem 获取更新内容:"+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 删除数据源
	@RequestMapping("delDataSource")
	public void todelDataSource(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer id = Integer.parseInt(request.getParameter("id"));
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("=,dataSourceId", id);
		Integer count = publicService.getDataImportCount(queryParams);
		HashMap<String, Object> queryParams2 = new HashMap<String, Object>();
		queryParams2.put("=,dataSourceId", id);
		Integer count2 = publicService.getDataExportCount(queryParams2);
		DataSource dataSource = null;
		if (count < 1 && count2 < 1) {
			dataSource = publicService.findDataSource(id);
			int logTime = 0;
			User logUser = publicService.findUser((Integer) request
					.getSession().getAttribute("userid"));
			try {
				baseService.deleteDataSource(dataSource);
			} catch (Exception e) {
				this.Log(
						logUser.getId(),
						"general_data",
						null,
						null,
						"【" + logUser.getNickname() + "】【删除】数据源【"
								+ dataSource.getName() + "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(
						logUser.getId(),
						"general_data",
						null,
						null,
						"【" + logUser.getNickname() + "】【删除】数据源【"
								+ dataSource.getName() + "】成功！", 0);
			}

		}
		String result = formatToJson(dataSource);
		// System.out.println("reu 删除数据源单条数据: "+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 批量处理数据源
	@RequestMapping("piLiangStatusDataSource")
	public void toPiLiangUserDel(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String idAll = request.getParameter("idAll");
		String status = request.getParameter("zhuangtai");
		String[] id = idAll.split(",");// 用逗号切割
		DataSource d = new DataSource();
		for (int i = 0; i < id.length; i++) {
			d = publicService.findDataSource(Integer.parseInt(id[i]));
			d.setStatus(Integer.parseInt(status));
			baseService.editDataSource(d);
		}
		String result = formatToJson(d);
		// System.out.println("result :"+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	/**
	 * 数据接口 模块
	 */
	// 数据接口查询
	@RequestMapping("findallDataInterface")
	@ResponseBody
	public void tofindAllDataInterface(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("findallDataSource");
		// System.out.println("路径:"+request.getRequestURL());
		String str = request.getRequestURL().toString();
		String url = str.substring(0, str.indexOf("/findallDataInterface.do"));
		Integer pageNumber = 15;
		Integer pageSize = 1;
		if (request.getParameter("page") != null) {
			pageSize = Integer.parseInt(request.getParameter("page"));
		} else {
			pageSize = 1;
		}
		String queryParam = request.getParameter("queryParams");
		String text = request.getParameter("text");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if (text != null && !"".equals(text)) {
			queryParams.put("%," + queryParam, text);
		}
		Integer count = publicService.getClassesCount(queryParams);
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		List<Classes> list = publicService.getClasses(queryParams, pageSize,
				pageNumber);
		for (int i = 0; i < list.size(); i++) {
			Classes classes = list.get(i);
			if (classes != null) {
				mp = new LinkedHashMap<String, Object>();
				mp.put("id", classes.getId());
				mp.put("description", "数据接口：" + classes.getNameZh()); // 中文名称
				mp.put("classNameEn", classes.getNameEn());
				mp.put("url", url + "/debugURL/" + classes.getNameEn()
						+ "&pageNumber=1&pageSize=15");
				mp.put("parameters", "当前页码(pageNumber)<br/>每页显示记录数(pageSize)"); // 参数
				mp.put("dataFormat", "JSON");
				r.add(mp);
			}
		}
		String result = formatToJson(r);
		// System.out.println("result:" +result);
		StringBuffer sb = new StringBuffer();
		int listsize = list.size();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 数据接口 在线调试
	@RequestMapping(value = "/dataInterfaceDebug", method = RequestMethod.POST)
	public void toDataInterfaceDebug(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("dataInterfaceDebug");
		String classNameEn = request.getParameter("classNameEn");
		String pageNumber = request.getParameter("pageNumber");
		String pageSize = request.getParameter("pageSize");
		if (pageNumber == null || "".equals(pageNumber)) {
			pageNumber = "1";
		}
		if (pageSize == null || "".equals(pageSize)) {
			pageSize = "15";
		}
		List<Map<String, Object>> list = dynamicService.getDynamicData(
				classNameEn, null, Integer.parseInt(pageNumber.trim()),
				Integer.parseInt(pageSize.trim()));
		Map<String, Object> map = new HashMap<String, Object>();
		for (int i = 0; i < list.size(); i++) {
			map.put("map" + i, list.get(i));
		}
		String resultString = formatToJson(map);
		super.pringWriterToPage(resultString, response);
	}

	@RequestMapping(value = { "/debugURL/{classNameEn}&pageNumber={pageNumber}&pageSize={pageSize}" }, method = RequestMethod.GET)
	public ModelAndView todebugURL(@PathVariable String classNameEn,
			@PathVariable String pageNumber, @PathVariable String pageSize,
			HttpServletRequest request, HttpServletResponse response) {
		List<Map<String, Object>> list = dynamicService.getDynamicData(
				classNameEn, null, Integer.parseInt(pageNumber.trim()),
				Integer.parseInt(pageSize.trim()));
//		Map<String, Object> map1 = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		for (int i = 0; i < list.size(); i++) {
			map.put("map" + i, list.get(i));
		}
		String resultString = formatToJson(map);
//		String result = stringToJSON(list.toString());
//		map.put("map", result);
//		map.put("map", map1);
		ModelAndView mav = new ModelAndView();
		mav.addObject("map", resultString);
		mav.setViewName("/modules/repository/debugURL");
		return mav;
	}

	/**
	 * ******************** 格式化JSON
	 */
	private boolean isTab = true;

	public String stringToJSON(String strJson) {
		// 计数tab的个数
		int tabNum = 0;
		StringBuffer jsonFormat = new StringBuffer();
		int length = strJson.length();
		for (int i = 0; i < length; i++) {
			char c = strJson.charAt(i);
			if (c == '{') {
				tabNum++;
				jsonFormat.append(c + "</br>");
				jsonFormat.append(getSpaceOrTab(tabNum));
			} else if (c == '}') {
				tabNum--;
				jsonFormat.append("</br>");
				jsonFormat.append(getSpaceOrTab(tabNum));
				jsonFormat.append(c);
			} else if (c == ',') {
				jsonFormat.append(c + "</br>");
				jsonFormat.append(getSpaceOrTab(tabNum));
			} else {
				jsonFormat.append(c);
			}
		}
		return jsonFormat.toString();
	}

	// 是空格还是tab
	public String getSpaceOrTab(int tabNum) {
		StringBuffer sbTab = new StringBuffer();
		for (int i = 0; i < tabNum; i++) {
			if (isTab) {
				sbTab.append("&nbsp;");
			} else {
				sbTab.append("    ");
			}
		}
		return sbTab.toString();
	}

	/**
	 * end *************
	 */

	/**
	 * 普通词表管理
	 */
	// 普通词表 分类管理查询
	@RequestMapping("findAllGeneralWordCategory")
	@ResponseBody
	public void tofindAllGeneralWordCategory(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		List<GeneralWordCategory> list = iWordService.getGeneralWordCategory();
		for (int i = 0; i < list.size(); i++) {
			GeneralWordCategory gwc = list.get(i);
			if (gwc != null) {
				mp = new LinkedHashMap<String, Object>();
				mp.put("size", list.size());
				mp.put("id", gwc.getId());
				mp.put("categoryName", gwc.getCategoryName());
				mp.put("categorySid", gwc.getCategorySid());
				r.add(mp);
			}
		}
		String result = formatToJson(r);
		// System.out.println(result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 普通词表 分类管理 插入 更新 分类管理
	@RequestMapping("generalWordCategoryAddEdit")
	@ResponseBody
	public void togeneralWordCategoryAddEdit(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		User logUser = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		String categoryName = request.getParameter("categoryName");
		String categorySid = request.getParameter("categorySid");
		GeneralWordCategory gwc = new GeneralWordCategory();
		gwc.setCategoryName(categoryName);
		gwc.setCategorySid(categorySid);
		int count = -1;
		if (!id.equals("0") && !id.equals("0") && id != null) {
			gwc.setId(Integer.parseInt(id));
			int logTime = 0;
			try {
				iWordService.editGeneralWordCategory(gwc);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【修改】词表分类【" + categoryName
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【修改】词表分类【" + categoryName
						+ "】成功！", 0);
			}

			count = 1;
		} else if (id.equals("0")) {
			int logTime = 0;
			try {
				iWordService.saveGeneralWordCategory(gwc);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】词表分类【" + categoryName
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】词表分类【" + categoryName
						+ "】成功！", 0);
			}

			count = 2;
		}
		String result = "{\"count\":" + count + "}";
		// System.out.println("resultadd    Dict 插入  更新：" + result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 普通词表 获取分类管理更新内容
	@RequestMapping("generalWordCategoryEditShow")
	public void togeneralWordCategoryEditShow(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("dataSourceEditShow 更新");
		String id = request.getParameter("id");
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		GeneralWordCategory gwc = iWordService.findGeneralWordCategory(Integer
				.parseInt(id));
		if (gwc != null) {
			dMap.put("id", gwc.getId());
			dMap.put("categoryName", gwc.getCategoryName());
			dMap.put("categorySid", gwc.getCategorySid());
		}
		String result = formatToJson(dMap);
		// System.out.println("result  generalWordCategoryEditShow 获取更新内容:"+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 普通词表 删除分类管理
	@RequestMapping("delgeneralWordCategory")
	public void todelGeneralWordCategory(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("=,generalWordCategoryId", id);
		Integer count = iWordService.getGeneralWordCount(queryParams);
		GeneralWordCategory generalWordCategory = null;
		if (count < 1) {
			generalWordCategory = new GeneralWordCategory();
			generalWordCategory = iWordService.findGeneralWordCategory(Integer
					.parseInt(id));
			int logTime = 0;
			User logUser = publicService.findUser((Integer) request
					.getSession().getAttribute("userid"));
			try {
				iWordService.deleteGeneralWordCategory(generalWordCategory);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【删除】词表分类【"
						+ generalWordCategory.getCategoryName()
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【删除】词表分类【"
						+ generalWordCategory.getCategoryName() + "】成功！", 0);
			}
		}
		String result = "{\"count\":" + count + "}";
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 普通词表查询
	@RequestMapping("findwordGeneralList")
	@ResponseBody
	public void tofindwordGeneralList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String GWordCategoryId = request.getParameter("GWordCategoryId");
		String showType = request.getParameter("showType").trim();
		Integer pageNumber = 10;
		Integer pageSize = 1;
		if (request.getParameter("page") != null) {
			pageSize = Integer.parseInt(request.getParameter("page"));
		} else {
			pageSize = 1;
		}
		String queryParam = request.getParameter("queryParams");
		String text = request.getParameter("text");
		String getType = request.getParameter("getType");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if ("缩略词展示".equals(showType)) {
			pageNumber = 90;
		}
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		Integer count = 0;
		List<GeneralWord> list = null;
		if (GWordCategoryId == null || "".equals(text)) {
			if (GWordCategoryId == null && !"".equals(text)) {
				if("1".equals(getType)){
					queryParams.put("=," + queryParam, text);
				}else{
					queryParams.put("%," + queryParam, text);
				}
				count = iWordService.getGeneralWordCount(queryParams);
				list = iWordService.getGeneralWord(queryParams, pageSize,
						pageNumber);
			} else if (GWordCategoryId != null && "".equals(text)) {
				queryParams.put("%,generalWordCategoryId", GWordCategoryId);
				count = iWordService.getGeneralWordCount(queryParams);
				list = iWordService.getGeneralWord(queryParams, pageSize,
						pageNumber);
			} else if (GWordCategoryId == null && "".equals(text)) {
				count = iWordService.getGeneralWordCount(null);
				list = iWordService.getGeneralWord(null, pageSize, pageNumber);
			}
		} else {
			queryParams.put("%," + queryParam, text);
			queryParams.put("%,generalWordCategoryId", GWordCategoryId);
			count = iWordService.getGeneralWordCount(queryParams);
			list = iWordService.getGeneralWord(queryParams, pageSize,
					pageNumber);
		}
		int listsize = list.size();
		if (listsize == 0) {
			mp = new LinkedHashMap<String, Object>();
			if (GWordCategoryId != null && !"".equals(GWordCategoryId)) {
				listsize = 1;
				mp.put("classTypeRed", "btn btn-red btn-sm btn-default");
			}
			r.add(mp);
		} else {
			for (int i = 0; i < list.size(); i++) {
				GeneralWord generalWord = list.get(i);
				mp = new LinkedHashMap<String, Object>();
				if (generalWord != null) {
					if (GWordCategoryId != null || "".equals(GWordCategoryId)) {
						mp.put("classTypeRed", "btn btn-red btn-sm btn-default");
					}
					mp.put("id", generalWord.getId());
					mp.put("wordName", generalWord.getWordName());
					if(generalWord.getWordPinyin() != null && !"".equals(generalWord.getWordPinyin())){
						mp.put("wordPinyin", generalWord.getWordPinyin());
					}else{
						mp.put("wordPinyin", "");
					}
					
					if(generalWord.getWordEnglish() != null && !"".equals(generalWord.getWordEnglish())){
						mp.put("wordEnglish", generalWord.getWordEnglish());
					}else{
						mp.put("wordEnglish", "");
					}
					
					if(generalWord.getWordInitial() != null && !"".equals(generalWord.getWordInitial())){
						mp.put("wordInitial", generalWord.getWordInitial());
					}else{
						mp.put("wordInitial", "");
					}
					if(generalWord.getWordScopeNote() != null && !"".equals(generalWord.getWordScopeNote())){
						mp.put("wordScopeNote", generalWord.getWordScopeNote());
					}else{
						mp.put("wordScopeNote", "");
					}
					if (generalWord.getGeneralWordCategoryId() != null
							&& !"".equals(generalWord
									.getGeneralWordCategoryId())) {
						GeneralWordCategory gwc = iWordService
								.findGeneralWordCategory(generalWord
										.getGeneralWordCategoryId());
						mp.put("generalWordCategoryId", gwc.getId());
						mp.put("generalWordCategoryName", gwc.getCategoryName());
					}
					r.add(mp);
				}
			}
		}
		String result = formatToJson(r);
		StringBuffer sb = new StringBuffer();

		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"count\":" + count + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 普通词表 插入 更新 分类管理
	@RequestMapping("generalWordAddEdit")
	@ResponseBody
	public void toGeneralWordAddEdit(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String generalWordCategoryId = request
				.getParameter("generalWordCategoryId");
		String wordName = request.getParameter("wordName");
		String wordPinyin = request.getParameter("wordPinyin");
		String wordEnglish = request.getParameter("wordEnglish");
		String wordInitial = request.getParameter("wordInitial");
		String wordScopeNote = request.getParameter("wordScopeNote");
		User logUser = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		GeneralWord generalWord = new GeneralWord();
		generalWord.setGeneralWordCategoryId(Integer
				.parseInt(generalWordCategoryId));
		generalWord.setWordName(wordName);
		generalWord.setWordPinyin(wordPinyin);
		generalWord.setWordEnglish(wordEnglish);
		generalWord.setWordInitial(wordInitial);
		generalWord.setWordScopeNote(wordScopeNote);
		// System.out.println(wordScopeNote);
		int count = -1;
		if (!id.equals("0") && !id.equals("0") && id != null) {
			generalWord.setId(Integer.parseInt(id));
			int logTime = 0;
			try {
				iWordService.editGeneralWord(generalWord);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【修改】词表数据列表【" + wordName
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【修改】词表数据列表【" + wordName
						+ "】成功！", 0);
			}

			count = 1;
		} else if (id.equals("0")) {
			int logTime = 0;
			try {
				iWordService.saveGeneralWord(generalWord);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】词表数据列表【" + wordName
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】词表数据列表【" + wordName
						+ "】成功！", 0);
			}

			count = 2;
		}
		String result = "{\"count\":" + count + "}";
		// System.out.println("resultadd   插入  更新：" + result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	/***/
	// 普通词表 添加修改 遍历 分类 【下拉框】 显示
	@RequestMapping("showXiaLaGeneralWordCategory")
	@ResponseBody
	public void toShowXiaLaGeneralWordCategory(HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		List<GeneralWordCategory> list = iWordService.getGeneralWordCategory();
		for (int i = 0; i < list.size(); i++) {
			GeneralWordCategory gwc = list.get(i);
			if (gwc != null) {
				mp = new LinkedHashMap<String, Object>();
				mp.put("id", gwc.getId());
				mp.put("categoryName", gwc.getCategoryName());
				r.add(mp);
			}
		}
		String resultString = formatToJson(r);
		// System.out.println("結果：" +resultString);
		super.pringWriterToPage(resultString, "application/json", response);
	}

	// 普通词表 获取分类管理更新内容
	@RequestMapping("generalWordEditShow")
	public void toGeneralWordEditShow(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String generalWordCategoryId = request
				.getParameter("generalWordCategoryId");
		HashMap<String, Object> dMap = new HashMap<String, Object>();

		if (!"0".equals(id)) {
			GeneralWord generalWord = iWordService.findGeneralWord(Integer
					.parseInt(id));
			if (generalWord != null) {
				dMap.put("generalWordCategoryId",
						generalWord.getGeneralWordCategoryId());
				dMap.put("id", generalWord.getId());
				dMap.put("wordName", generalWord.getWordName());
				dMap.put("wordPinyin", generalWord.getWordPinyin());
				dMap.put("wordEnglish", generalWord.getWordEnglish());
				dMap.put("wordInitial", generalWord.getWordInitial());
				// System.out.println("generalWord.getWordScopeNote():  "+generalWord.getWordScopeNote());
				dMap.put("wordScopeNote", generalWord.getWordScopeNote());
			}
		} else {
			dMap.put("generalWordCategoryId", generalWordCategoryId);
		}

		String result = formatToJson(dMap);
		// System.out.println("result  获取更新内容:"+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 删除 普通词表
	@RequestMapping("delgeneralWord")
	public void todelgeneralWord(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		GeneralWord generalWord = new GeneralWord();
		generalWord = iWordService.findGeneralWord(Integer.parseInt(id));
		int logTime = 0;
		User logUser = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		try {
			iWordService.deleteGeneralWord(generalWord);
		} catch (Exception e) {
			this.Log(
					logUser.getId(),
					"general_data",
					null,
					null,
					"【" + logUser.getNickname() + "】【删除】词表数据列表【"
							+ generalWord.getWordName() + "】失败！请检查数据是否正确！", 1);
			logTime = 1;
			e.printStackTrace();
		}
		if (logTime == 0) {
			this.Log(
					logUser.getId(),
					"general_data",
					null,
					null,
					"【" + logUser.getNickname() + "】【删除】词表数据列表【"
							+ generalWord.getWordName() + "】成功！", 0);
		}

		String result = formatToJson(generalWord);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 模板下载
	@RequestMapping("generalWordImportTempletdownload")
	public void generalWordImportTempletdownload(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		String fileName = "general_word.xml";
		String path = request.getSession().getServletContext()
				.getRealPath("/template/");
		generalWordExport(request, response, fileName, path);

	}

	// 工具类 生成模板
	public void togeneralWordImp(String path, String downtype) {
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		Integer count = Integer.parseInt(iWordService.getGeneralWordCount(
				queryParams).toString());
		List<GeneralWord> list1 = iWordService.getGeneralWord(queryParams, 1,
				count);
		List<HashMap<String, Object>> list2 = new ArrayList<HashMap<String, Object>>();
		Integer aInteger = Integer.parseInt(downtype);
		if (aInteger == 1) {
			LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
			for (int i = 0; i < list1.size(); i++) {
				GeneralWord generalWord = list1.get(i);
				String generalWordCategoryName = "";
				if (generalWord.getGeneralWordCategoryId() != null) {
					GeneralWordCategory gwc = iWordService
							.findGeneralWordCategory(generalWord
									.getGeneralWordCategoryId());
					generalWordCategoryName = gwc.getCategoryName();
				}

				map.put("分类名称", generalWordCategoryName);
				map.put("词名称", generalWord.getWordName());
				map.put("汉语拼音", generalWord.getWordPinyin());
				map.put("英文译名", generalWord.getWordEnglish());
				map.put("词首字母", generalWord.getWordInitial());
				map.put("含义注释", generalWord.getWordScopeNote());
			}
			list2.add(map);

		}
		LinkedHashMap<String, Object> map2 = new LinkedHashMap<String, Object>();
		for (int i = 0; i < list1.size(); i++) {
			GeneralWord generalWord = list1.get(i);
			String generalWordCategoryName = "";
			if (generalWord.getGeneralWordCategoryId() != null) {
				GeneralWordCategory gwc = iWordService
						.findGeneralWordCategory(generalWord
								.getGeneralWordCategoryId());
				generalWordCategoryName = gwc.getCategoryName();
			}
			map2.put("分类名称", generalWordCategoryName);
			map2.put("词名称", generalWord.getWordName());
			map2.put("汉语拼音", generalWord.getWordPinyin());
			map2.put("英文译名", generalWord.getWordEnglish());
			map2.put("词首字母", generalWord.getWordInitial());
			map2.put("含义注释", generalWord.getWordScopeNote());
		}
		list2.add(map2);
		DBUtils.writeExcel(path + "general_word.xml", list2, aInteger);
	}

	// 上传excel导入
	@RequestMapping("generalWordImp")
	public void generalWordImp(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 上传附件
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("uploadify");
		// 获取服务器地址
		ServletContext sc = request.getSession().getServletContext();
		// 附件存放服务器路径
		String dir = "";
		String fileName = file.getOriginalFilename();
		Long _l = System.nanoTime();
		String _extName = fileName.substring(fileName.indexOf("."));
		dir = sc.getRealPath("/upload/xmlImport/");
		if (!new File(dir).exists()) {
			new File(dir).mkdirs();
		}
		fileName = _l + _extName;
		String uploadPath = "/upload/xmlImport/" + fileName;
		String responseStr = "";
		try {
			FileUtils.writeByteArrayToFile(new File(dir, fileName),
					file.getBytes());// 服务器中生成文件
			responseStr = fileName;
		} catch (IOException e) {
			e.printStackTrace();
			responseStr = "上传失败";
		}
		response.getWriter().print(uploadPath);
	}

	// 数据导入{导入数据处理}
	@RequestMapping("generalWordImportHandle")
	public void togeneralWordImportHandle(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		//访问前缀	
		String uploadPath =  XxlConfClient.get("dal.file.server", "") +"/";
		//磁盘前缀
		String adjunctPath =  XxlConfClient.get("dal.file.path", "");
		// 解析文件，生成document对象
		String path = request.getParameter("path");
		DocumentBuilder builder = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder();
		/*String path = request.getSession().getServletContext().getRealPath("/")
				+ id;*/
		path = path.replaceAll(uploadPath, "");
		Document document = builder.parse(new File(adjunctPath+path));

		// 生成XPath对象
		XPath xpath = XPathFactory.newInstance().newXPath();

		// 获取节点集合
		NodeList f_subject = (NodeList) xpath.evaluate("//general_word",
				document, XPathConstants.NODESET);
		for (int i = 0; i < f_subject.getLength(); i++) {
			Node subject = f_subject.item(i);
			// 属性id
			String iddata = xpath.evaluate("@id", subject,
					XPathConstants.STRING).toString();

			// 一级所有值

			String word_name = xpath.evaluate("word_name", subject,
					XPathConstants.STRING).toString();
			String word_pinyin = xpath.evaluate("word_pinyin", subject,
					XPathConstants.STRING).toString();
			String word_english = xpath.evaluate("word_english", subject,
					XPathConstants.STRING).toString();
			String word_initial = xpath.evaluate("word_initial", subject,
					XPathConstants.STRING).toString();
			String word_scope_note = xpath.evaluate("word_scope_note", subject,
					XPathConstants.STRING).toString();
			NodeList general_word_category = (NodeList) xpath.evaluate(
					"general_word_category", subject, XPathConstants.NODESET);

			// 二级节点内容
			String category_name = "";
			String category_sid = "";
			String category_dataid = "";
			for (int j = 0; j < general_word_category.getLength(); j++) {
				Node subjectWord = general_word_category.item(j);
				// 二级节点所以值
				category_name = xpath.evaluate("category_name", subjectWord,
						XPathConstants.STRING).toString();
				category_sid = xpath.evaluate("category_sid", subjectWord,
						XPathConstants.STRING).toString();

				// 二级节点属性
				category_dataid = xpath.evaluate("@data_id", subjectWord,
						XPathConstants.STRING).toString();

			}

			// 词表分类
			Integer count = iWordService.getGeneralWordCount(null);
			// System.out.println(category_dataid);
			boolean falg2 = true;

			List<GeneralWordCategory> generalWordCategories = iWordService
					.getGeneralWordCategory();
			for (int k = 0; k < generalWordCategories.size(); k++) {
				GeneralWordCategory generalWordCategory = generalWordCategories
						.get(k);
				if (generalWordCategory.getCategoryName().equals(category_name)) {
					falg2 = false;
					break;// 插重，不插入。
				}
			}
			if (falg2) {
				GeneralWordCategory generalWordCategory = new GeneralWordCategory();

				generalWordCategory.setCategoryName(category_name);
				generalWordCategory.setCategorySid(category_sid);
				// System.out.println(category_dataid);
				
				generalWordCategory.setId(Integer.parseInt(category_dataid));
				iWordService.saveGeneralWordCategory(generalWordCategory);

			}
			GeneralWordCategory generalWordCategory2 = new GeneralWordCategory();
			List<GeneralWordCategory> generalWordCategories2 = iWordService
					.getGeneralWordCategory();
			for (int k = 0; k < generalWordCategories2.size(); k++) {
				GeneralWordCategory generalWordCategory = generalWordCategories2
						.get(k);
				if (generalWordCategory.getCategoryName().equals(category_name)) {
					generalWordCategory2 = generalWordCategories2.get(k);
					break;// 插重，不插入。
				}
			}
			// 词表插入
			Integer cont2 = iWordService.getGeneralWordCount(null);

			// System.out.println(cont1);
			List<GeneralWord> generalWords = iWordService.getGeneralWord(null,
					1, cont2);
			boolean falg = true;
			for (int j = 0; j < generalWords.size(); j++) {
				GeneralWord generalWord = generalWords.get(j);
				if (generalWord.getWordName().equals(word_name))// 查重,false不插入
				{
					falg = false;
					break;
				}
			}
			if (falg) {
				GeneralWord generalWord = new GeneralWord();
				// generalWord.setId(Integer.parseInt(iddata));
				generalWord.setWordName(word_name);
				generalWord.setWordPinyin(word_pinyin);
				generalWord.setWordEnglish(word_english);
				generalWord.setWordInitial(word_initial);
				generalWord.setWordScopeNote(word_scope_note);
				generalWord.setGeneralWordCategoryId(generalWordCategory2
						.getId());
				iWordService.saveGeneralWord(generalWord);

			}
			 System.out.println(word_name + "/" + word_pinyin+ "/"
			 +word_english+"/"+word_initial
			 +"/"+word_scope_note);

		}
		String result = "{\"result\":" + "\"ok\"}";
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	public void WordExportdownload(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// generalWordExportdownload();
		String fileName = "generalWord" + ".xml";
		String path = "D://";
		generalWordExport(request, response, fileName, path);

	}

	public void generalWordExport(HttpServletRequest request,
			HttpServletResponse response, String fileName, String path)
			throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName="
				+ fileName);
		try {
			// 这个download目录为啥建立在classes下的
			InputStream inputStream = new FileInputStream(new File(path + "/"
					+ File.separator + fileName));
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			// 这里主要关闭。
			os.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 叙词表管理
	 */

	// 叙词表 插入 更新 叙词表(主题款目词表)
	@RequestMapping("thesauriWordAddEdit")
	@ResponseBody
	public void toThesauriWordAddEdit(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String wordName = request.getParameter("wordName");
		String isTopTerm = request.getParameter("isTopTerm");
		String wordPinyin = request.getParameter("wordPinyin");
		String wordEnglish = request.getParameter("wordEnglish");
		String thesauriWordCategoryId = request.getParameter("thesauriWordCategoryId");
		String scopeNote = request.getParameter("scopeNote");
		String usageNote = request.getParameter("usageNote");
		String historicalNote = request.getParameter("historicalNote");
		String wordFormal = request.getParameter("wordFormal");
		String wordClasses = request.getParameter("wordClasses");
		User logUser = publicService.findUser((Integer) request.getSession().getAttribute("userid"));

		ThesauriWord thesauriWord = new ThesauriWord();
		thesauriWord.setWordName(wordName);
		thesauriWord.setIsTopTerm(isTopTerm);
		thesauriWord.setWordPinyin(wordPinyin);
		thesauriWord.setWordEnglish(wordEnglish);
		thesauriWord.setThesauriWordModuleId(Integer.parseInt(wordClasses));
		if (thesauriWordCategoryId != null&& !thesauriWordCategoryId.equals("")) {
			String[] thesauriWordCategoryIds = thesauriWordCategoryId.split(";");
			String cids = "";
			for (int i = 0; i < thesauriWordCategoryIds.length; i++) {
				ThesauriWordCategory thesauriWordCategory = iWordService.findThesauriWordCategory(Integer.parseInt(thesauriWordCategoryIds[i]));
				cids += thesauriWordCategory.getCategorySid() + ";";
			}
			thesauriWord.setThesauriWordCategoryIds(cids);
		}
		thesauriWord.setScopeNote(scopeNote);
		thesauriWord.setUsageNote(usageNote);
		thesauriWord.setHistoricalNote(historicalNote);
		thesauriWord.setWordFormal(Integer.parseInt(wordFormal));
		int count = -1;
		if (!id.equals("0") && !id.equals("0") && id != null) {
			thesauriWord.setId(Integer.parseInt(id));
			int logTime = 0;
			try {
				iWordService.editThesauriWord(thesauriWord);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【修改】叙词表数据【" + wordName
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【修改】叙词表数据【" + wordName
						+ "】成功！", 0);
			}

			count = 1;
		} else if (id.equals("0")) {
			int logTime = 0;
			try {
				iWordService.saveThesauriWord(thesauriWord);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】叙词表数据【" + wordName
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】叙词表数据【" + wordName
						+ "】成功！", 0);
			}

			count = 2;
		}
		String result = "{\"count\":" + count + "}";
		// System.out.println("resultadd    Dict 插入  更新：" + result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 叙词表 获取 叙词表(主题款目词表) 更新内容
	@RequestMapping("thesauriWordEditShow")
	public void toThesauriWordEditShow(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		ThesauriWord thesauriWord = iWordService.findThesauriWord(Integer.parseInt(id));
		if (thesauriWord != null) {
			dMap.put("id", thesauriWord.getId().toString());
			dMap.put("wordName", thesauriWord.getWordName());
			dMap.put("isTopTerm", thesauriWord.getIsTopTerm());
			dMap.put("wordPinyin", thesauriWord.getWordPinyin());
			dMap.put("wordEnglish", thesauriWord.getWordEnglish());
			dMap.put("thesauriWordModuleId", thesauriWord.getThesauriWordModuleId());
			if (!"0".equals(thesauriWord.getThesauriWordCategoryIds())
					&& !thesauriWord.getThesauriWordCategoryIds()
							.equals("null")
					&& !"".equals(thesauriWord.getThesauriWordCategoryIds())) {
				String[] fanchous = thesauriWord.getThesauriWordCategoryIds()
						.split(";");
				String fanChouId = "";
				String fanChouname = "";
				for (int i = 0; i < fanchous.length; i++) {
					HashMap<String, Object> queryParams = new LinkedHashMap<String, Object>();
					queryParams.put("=,categorySid", fanchous[i]);
					List<ThesauriWordCategory> twc2 = iWordService
							.getThesauriWordCategory(
									queryParams,
									1,
									iWordService.getThesauriWordCategoryCount(
											queryParams).intValue());
					for (int j = 0; j < twc2.size(); j++) {
						ThesauriWordCategory thesauriWordCategory = twc2.get(j);
						fanChouId += thesauriWordCategory.getId() + ";";
						fanChouname += thesauriWordCategory.getCategoryName()
								+ ";";
					}
				}
				dMap.put("thesauriWordCategoryId", fanChouId);
				dMap.put("thesauriWordCategoryName", fanChouname);
			}
			dMap.put("scopeNote", thesauriWord.getScopeNote());
			dMap.put("usageNote", thesauriWord.getUsageNote());
			dMap.put("historicalNote", thesauriWord.getHistoricalNote());
			dMap.put("wordFormal", thesauriWord.getWordFormal());
		}
		String result = formatToJson(dMap);
		// System.out.println("result  获取更新内容:"+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 叙词表 叙词表(主题款目词表) 查询
	@RequestMapping("findThesauriWordList")
	@ResponseBody
	public void tofindThesauriWordList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer pageNumber = 10;
		Integer pageSize = 1;
		if (request.getParameter("page") != null) {
			pageSize = Integer.parseInt(request.getParameter("page"));
		} else {
			pageSize = 1;
		}
		String text = request.getParameter("text");
		String wordClasses = request.getParameter("wordClasses");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("=,thesauri_word_module_id", wordClasses);
		List<HashMap<String, String>> r = new ArrayList<HashMap<String, String>>();
		LinkedHashMap<String, String> mp = null;
		Integer count = 0;
		List<ThesauriWord> list = null;
		if (!"".equals(text) && text != null) {
			
		    queryParams.put("%,wordName", text);
			count = iWordService.getThesauriWordCount(queryParams);
			list = iWordService.getThesauriWord(queryParams, pageSize,pageNumber);
		} else {
			count = iWordService.getThesauriWordCount(queryParams);
			list = iWordService.getThesauriWord(queryParams, pageSize, pageNumber);
		}
		// System.out.println("count:"+count+"   wordName:"+text);
		String thesauriWordId = request.getParameter("thesauriWordId");
		int category = Integer.parseInt(request.getParameter("category"));
		// List<HashMap<String, String>> listTWR =
		// iWordService.getThesauriWordReference(thesauriWordId);
		int j = 0;
		for (int i = 0; i < list.size(); i++) {
			boolean flag = false;
			ThesauriWord thesauriWord = list.get(i);
			mp = new LinkedHashMap<String, String>();
			if (category != 0) {
				if (thesauriWord.getId().equals(thesauriWordId)) {
					flag = true;
				}
			}
			if (flag != true && thesauriWord != null) {
				j = j + 1;
				mp.put("id", thesauriWord.getId().toString());
				mp.put("wordName", thesauriWord.getWordName());
				mp.put("wordPinyin", thesauriWord.getWordPinyin());
				mp.put("wordEnglish", thesauriWord.getWordEnglish());
				if (!"null".equals(thesauriWord.getThesauriWordCategoryIds())
						&& !"".equals(thesauriWord.getThesauriWordCategoryIds())) {
					String[] fanchous = thesauriWord
							.getThesauriWordCategoryIds().split(";");
					String fanChouId = "";
					String fanChouname = "";
					for (int k = 0; k < fanchous.length; k++) {
						HashMap<String, Object> queryParams2 = new HashMap<String, Object>();
						queryParams2.put("=,categorySid", fanchous[k]);
						List<ThesauriWordCategory> twc2 = iWordService
								.getThesauriWordCategory(
										queryParams2,
										1,
										iWordService
												.getThesauriWordCategoryCount(
														queryParams2)
												.intValue());
						for (int l = 0; l < twc2.size(); l++) {
							ThesauriWordCategory thesauriWordCategory = twc2
									.get(l);
							fanChouId += thesauriWordCategory.getId() + ";";
							fanChouname += thesauriWordCategory
									.getCategoryName() + ";";

						}
					}

					mp.put("thesauriWordCategoryId", fanChouId);
					mp.put("thesauriWordCategoryName", fanChouname);
				} else {
					mp.put("thesauriWordCategoryId", "");
					mp.put("thesauriWordCategoryName", "");
				}
				r.add(mp);
			}
		}
		String result = formatToJson(r);
		// System.out.println("result:" +result);
		StringBuffer sb = new StringBuffer();
		sb.append("{\"listsize\":" + j + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		// System.out.println("sb:"+sb);
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 叙词表 叙词表(主题款目词表) 删除
	@RequestMapping("delThesauriWord")
	public void toDelThesauriWord(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String id = request.getParameter("id").trim();

		HashMap<String, Object> queryParams = new LinkedHashMap<String, Object>();
		queryParams.put("=,thesauriWordId", id);
		List<ThesauriWordReference> list = iWordService
				.getThesauriWordReference(queryParams, 1, iWordService
						.getThesauriWordReferenceCount(queryParams).intValue());
		ThesauriWord thesauriWord = null;
		int count = 1;
		// System.out.println(list.size());
		if (list.size() == 0) {
			thesauriWord = new ThesauriWord();
			thesauriWord = iWordService.findThesauriWord(Integer.parseInt(id));
			int logTime = 0;
			User logUser = publicService.findUser((Integer) request
					.getSession().getAttribute("userid"));
			try {

				iWordService.deleteThesauriWord(thesauriWord);
			} catch (Exception e) {
				this.Log(
						logUser.getId(),
						"general_data",
						null,
						null,
						"【" + logUser.getNickname() + "】【删除】叙词表数据【"
								+ thesauriWord.getWordName() + "】失败！请检查数据是否正确！",
						1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null,
						"【" + logUser.getNickname() + "】【删除】叙词表数据【"
								+ thesauriWord.getWordName() + "】成功！", 0);
			}

			count = 0;
		}
		String result = "{\"count\":" + count + "}";
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 叙词表 款目词参照项查询
	@RequestMapping("findAllthesauriWordReference")
	@ResponseBody
	public void tofindAllthesauriWordReference(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("tofindAllthesauriWordReference");
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		String thesauriWordId = request.getParameter("thesauriWordId").trim();
		// System.out.println("th   "+thesauriWordId);
		queryParams.put("=,thesauriWordId", thesauriWordId);
		LinkedHashMap<String, Object> mp = null;
		List<ThesauriWordReference> list = iWordService
				.getThesauriWordReference(queryParams, 1, iWordService
						.getThesauriWordReferenceCount(queryParams).intValue());
		ThesauriWord thesauriWord2 = iWordService.findThesauriWord(Integer
				.parseInt(thesauriWordId));// 款目词关联词
		for (ThesauriWordReference m : list) {
			ThesauriWord thesauriWord = iWordService.findThesauriWord(Integer
					.parseInt(m.getReferenceWordId()));
			mp = new LinkedHashMap<String, Object>();
			mp.put("size", "" + list.size());
			mp.put("thesauriWordId", thesauriWord2.getId());
			mp.put("thesauriWordName", thesauriWord2.getWordName());
			mp.put("referenceWordName", thesauriWord.getWordName());
			mp.put("referenceWordId", m.getReferenceWordId());
			mp.put("referenceRelationLabel", m.getReferenceRelationLabel());
			r.add(mp);
		}

		String result = formatToJson(r);
		StringBuffer sb;
		if (list.size() <= 0) {
			ThesauriWord t = iWordService.findThesauriWord(Integer
					.parseInt(thesauriWordId));
			LinkedHashMap<String, Object> mp2 = new LinkedHashMap<String, Object>();
			mp2.put("thesauriWordName", t.getWordName());
			mp2.put("thesauriWordId", t.getId());
			result = formatToJson(mp2);
			sb = new StringBuffer();
			sb.append("{\"result\":" + result + "}");
		} else {
			sb = new StringBuffer();
			sb.append("{\"result\":" + result + "}");
		}
		// System.out.println(sb);
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 叙词表 款目词参照项查询 列表
	@RequestMapping("findAllthesauriWordReferenceLieBiao")
	@ResponseBody
	public void tofindAllthesauriWordReferenceLieBiao(
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Integer pageNumber = 10;
		Integer pageSize = 1;
		if (request.getParameter("page") != null) {
			pageSize = Integer.parseInt(request.getParameter("page"));
		} else {
			pageSize = 1;
		}
		String text=request.getParameter("text");
		//URLDecoder.decode(request.getParameter("name"),"utf-8"); 
		//String text = new String(request.getParameter("text").getBytes("ISO-8859-1"),"UTF-8"); 
		//String text = URLDecoder.decode(request.getParameter("text"),"GBK");
		//String text = URLDecoder.decode("%E9%98%BF","UTF-8");
		String fc = request.getParameter("fc");
		String type = request.getParameter("type");
		String wordClasses = request.getParameter("wordClasses");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if (text != null && !"".equals(text)) {
			if("1".equals(type)){
				queryParams.put("=,wordName", text);
			}else {
				queryParams.put("%,wordName", text);
			}
		}
		if (fc != null && !"".equals(fc)) {
			queryParams.put("%,thesauriWordCategoryIds", fc);
		}
		queryParams.put("=,thesauri_word_module_id", wordClasses);
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		Integer count = 0;
		List<ThesauriWord> list = null;
		if (!"".equals(text) || !"".equals(fc)) {
			count = iWordService.getThesauriWordCount(queryParams);
			list = iWordService.getThesauriWord(queryParams, pageSize,
					pageNumber);
		} else {
			count = iWordService.getThesauriWordCount(queryParams);
			list = iWordService.getThesauriWord(queryParams, pageSize, pageNumber);
		}
		List<ThesauriWordReference> list2 = null;
		int listsize = list.size();

		for (int i = 0; i < list.size(); i++) {
			ThesauriWord thesauriWord = list.get(i);
			if (thesauriWord != null) {
				HashMap<String, Object> queryParams2 = new HashMap<String, Object>();
				queryParams2.put("=,thesauriWordId", thesauriWord.getId().toString());

				list2 = iWordService.getThesauriWordReference(queryParams2, 1,iWordService.getThesauriWordReferenceCount(queryParams2).intValue());
				mp = new LinkedHashMap<String, Object>();
				mp.put("countsize", "" + list2.size());
				mp.put("thesauriWordId", thesauriWord.getId());
				ThesauriWord pidThesauriWord =iWordService.findThesauriWord(thesauriWord.getWordPid());
				if(pidThesauriWord != null ){
					mp.put("thesauriWordPidName", pidThesauriWord.getWordName());
					mp.put("thesauriWordPid", thesauriWord.getWordPid());
				}else{
					mp.put("thesauriWordPid", "");
				}
				mp.put("thesauriWordName", thesauriWord.getWordName());
				mp.put("wordEnglish", thesauriWord.getWordEnglish());
				List<HashMap<String, Object>> r2 = new ArrayList<HashMap<String, Object>>();
				LinkedHashMap<String, Object> mp2 = null;
				for (ThesauriWordReference m : list2) {
					ThesauriWord tw = iWordService.findThesauriWord(Integer.parseInt(m.getReferenceWordId().toString()));
					mp2 = new LinkedHashMap<String, Object>();
					mp2.put("referenceWordName", tw.getWordName());
					mp2.put("referenceWordId", m.getReferenceWordId());
					mp2.put("referenceRelationLabel",m.getReferenceRelationLabel());
					r2.add(mp2);
				}
				mp.put("thesauriWordReference", r2);
				
				//判断有无下级
				HashMap<String, Object> queryJunior = new LinkedHashMap<String, Object>();
				queryJunior.put("=,wordPid", thesauriWord.getId());
				int JuniorCount =iWordService.getThesauriWordCount(queryJunior);
				mp.put("JuniorCount", JuniorCount);
				r.add(mp);
			}
		}
		HashMap<String, Object> queryRelationParams = new LinkedHashMap<String, Object>();
        queryRelationParams.put("=,thesauri_word_module_id", wordClasses);
		List<ThesauriWordRelation> thesauriWordRelationList = iWordService.getThesauriWordRelation(queryRelationParams, 1, iWordService.getThesauriWordRelationCount(queryRelationParams));
        LinkedHashMap<String, Object> keyValue = new LinkedHashMap<String, Object>(); 
        for (int i = 0; i < thesauriWordRelationList.size(); i++) {
            ThesauriWordRelation thesauriWordRelation = thesauriWordRelationList.get(i);
            keyValue.put(thesauriWordRelation.getNameEn(), thesauriWordRelation.getNameZh()+"("+thesauriWordRelation.getNameEn()+")");
        }
		String result = formatToJson(r);
		// System.out.println("result:" +result);
		StringBuffer sb = new StringBuffer();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":"+ (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"count\":" + count + ",");
		sb.append("\"result\":" + result + ",");
		sb.append("\"keys\":" + formatToJson(keyValue));
		sb.append("}");
		// System.out.println(sb);
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 叙词表 添加关联(款目词参照项)
	@RequestMapping("addThesauriWordReference")
	@ResponseBody
	public void toAddThesauriWordReference(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String thesauriWordId = request.getParameter("thesauriWordId");
		String referenceWordId = request.getParameter("referenceWordId");
		String referenceRelationLabel = request.getParameter("referenceRelationLabel");
		String wordClasses = request.getParameter("wordClasses");
		String regEx = "\\((.*)\\)";
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(referenceRelationLabel);

		while (matcher.find()) {
			referenceRelationLabel = matcher.group(1);
		}

		/*
		 * if ("Z)".equals(ret)) { referenceRelationLabel = "Z"; } else if
		 * ("Y)".equals(ret)) { referenceRelationLabel = "Y"; } else if
		 * ("D)".equals(ret)) { referenceRelationLabel = "D"; } else if
		 * ("S)".equals(ret)) { referenceRelationLabel = "S"; } else if
		 * ("F)".equals(ret)) { referenceRelationLabel = "F"; } else if
		 * ("C)".equals(ret)) { referenceRelationLabel = "C"; }
		 */
		// System.out.println(thesauriWordId+"    "+referenceWordId+"    "+referenceRelationLabel);
		int count = 0;
		String twordName = "";
		ThesauriWordReference thesauriWordReference = null;
		if (thesauriWordId != null && referenceWordId != null&& !"".equals(referenceRelationLabel)) {
			String reId[] = referenceWordId.split(",");
			for (int i = 0; i < reId.length; i++) {
				HashMap<String, Object> queryParams = new LinkedHashMap<String, Object>();
				thesauriWordReference = new ThesauriWordReference();
				queryParams.put("=,thesauriWordId", thesauriWordId);
				queryParams.put("=,referenceWordId", reId[i]);
				queryParams.put("=,referenceRelationLabel",referenceRelationLabel);
				thesauriWordReference.setThesauriWordId(thesauriWordId);
				thesauriWordReference.setReferenceWordId(reId[i]);
				thesauriWordReference.setReferenceRelationLabel(referenceRelationLabel);
				thesauriWordReference.setThesauriWordModuleId(Integer.parseInt(wordClasses));
				Integer twrsize = iWordService.getThesauriWordReferenceCount(queryParams);
				if (twrsize <= 0) {
					int logTime = 0;
					User logUser = publicService.findUser((Integer) request.getSession().getAttribute("userid"));
					ThesauriWord generalWord = iWordService.findThesauriWord(Integer.parseInt(reId[i]));
					try {
						iWordService.saveThesauriWordReference(thesauriWordReference);
					} catch (Exception e) {
						this.Log(logUser.getId(), "general_data", null, null,
								"【" + logUser.getNickname() + "】【新增】叙词表参照项【"
										+ generalWord.getWordName()
										+ "】失败！请检查数据是否正确！", 1);
						logTime = 1;
						e.printStackTrace();
					}
					if (logTime == 0) {
						this.Log(logUser.getId(), "general_data", null, null,
								"【" + logUser.getNickname() + "】【新增】叙词表参照项【"
										+ generalWord.getWordName() + "】成功！", 0);
					}

				} else {
					ThesauriWord t = iWordService.findThesauriWord(Integer.parseInt(reId[i]));
					twordName = t.getWordName();
					count = 1;
					break;
				}
			}
		} else {
			count = 1;
		}
		LinkedHashMap<String, Object> mp = new LinkedHashMap<String, Object>();
		mp.put("twordName", twordName);
		String result = formatToJson(mp);
		StringBuffer sb = new StringBuffer();
		sb.append("{\"count\":" + count + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		// System.out.println("resultadd    twr2 插入  更新：" + result);
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 叙词表 关联 删除
	@RequestMapping("delThesauriWordReference")
	public void toDelThesauriWordReference(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		User logUser = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		String thesauriWordId = request.getParameter("thesauriWordId");
		String source = request.getParameter("source");
		// System.out.println(source);
		if ("Z".equals(source) || "族(Z)".equals(source)) {
			source = "Z";
		} else if ("Y".equals(source) || "用(Y)".equals(source)) {
			source = "Y";
		} else if ("D".equals(source) || "代(D)".equals(source)) {
			source = "D";
		} else if ("S".equals(source) || "属(S)".equals(source)) {
			source = "S";
		} else if ("F".equals(source) || "分(F)".equals(source)) {
			source = "F";
		} else if ("C".equals(source) || "参(C)".equals(source)) {
			source = "C";
		}
		// System.out.println(source);
		int count = 0;
		HashMap<String, Object> queryParams = new LinkedHashMap<String, Object>();
		queryParams.put("=,thesauriWordId", id);
		queryParams.put("=,referenceWordId", thesauriWordId);
		queryParams.put("=,referenceRelationLabel", source);
		List<ThesauriWordReference> thesauriWordReferenceList = iWordService
				.getThesauriWordReference(queryParams, 1, iWordService
						.getThesauriWordReferenceCount(queryParams).intValue());
		// System.out.println(thesauriWordId+"    "+id+"    "+source);
		for (int i = 0; i < thesauriWordReferenceList.size(); i++) {
			ThesauriWordReference thesauriWordReference = thesauriWordReferenceList
					.get(i);
			int logTime = 0;
			ThesauriWord generalWord = iWordService.findThesauriWord(Integer
					.parseInt(thesauriWordId));
			try {
				iWordService.deleteThesauriWordReference(thesauriWordReference);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null,
						"【" + logUser.getNickname() + "】【删除】叙词表参照项【"
								+ generalWord.getWordName() + "】失败！请检查数据是否正确！",
						1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null,
						"【" + logUser.getNickname() + "】【删除】叙词表参照项【"
								+ generalWord.getWordName() + "】成功！", 0);
			}

			count = 1;
		}
		String result = "{\"count\":" + count + "}";
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// zTree结构查询
	@RequestMapping("findallThesauriWordCategoryZTree")
	@ResponseBody
	public void tofindAllThesauriWordCategoryZTree(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
	    String classesId = request.getParameter("classesId");
		String thesauriWordCategoryId = request.getParameter("thesauriWordCategoryId");
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		HashMap<String, Object> queryParams = new LinkedHashMap<String, Object>();
		queryParams.put("=,thesauri_word_module_id", classesId);
		List<ThesauriWordCategory> list = iWordService.getThesauriWordCategory(queryParams, 1, iWordService.getThesauriWordCategoryCount(queryParams));
		for (int i = 0; i < list.size(); i++) {
			ThesauriWordCategory twc = list.get(i);
			// System.out.println("pid:"+twc.getParentId());
			mp = new LinkedHashMap<String, Object>();
			mp.put("id", twc.getId());
			mp.put("name", twc.getCategoryName());
			mp.put("fcId", twc.getCategorySid());
			if (twc.getParentId() != null) {
				mp.put("pId", twc.getParentId());
			} else {
				mp.put("pId", "0");
			}
			if (thesauriWordCategoryId != null) {
				String[] thesauriWordCategoryIds = thesauriWordCategoryId
						.split(";");
				for (int j = 0; j < thesauriWordCategoryIds.length; j++) {
					if (twc.getId().equals(thesauriWordCategoryIds[j])) {
						mp.put("page", "0");
					}
				}
			}

			r.add(mp);
		}
		String result = formatToJson(r);
		// System.out.println("result  【zTree】  :" + result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 叙词表 叙词表 范畴 插入 更新
	@RequestMapping("thesauriWordCategoryAddEdit")
	@ResponseBody
	public void toThesauriWordCategoryAddEdit(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String categoryName = request.getParameter("categoryName");
		String categorySid = request.getParameter("categorySid");
		String parentId = request.getParameter("parentId");
		String classesId = request.getParameter("classesId");
		User logUser = publicService.findUser((Integer) request.getSession().getAttribute("userid"));
		// System.out.println("pid :"+parentId+"  id:"+id);
		ThesauriWordCategory twc = new ThesauriWordCategory();
		twc.setCategoryName(categoryName);
		twc.setCategorySid(categorySid);
		twc.setThesauriWordModuleId(Integer.parseInt(classesId));
		if (parentId != null && !"".equals(parentId)) {
			twc.setParentId(parentId);
		} else {
			twc.setParentId("0");
		}
		int count = -1;
		if (!id.equals("0") && !id.equals("0") && id != null) {
			twc.setId(Integer.parseInt(id));
			int logTime = 0;
			try {
				iWordService.editThesauriWordCategory(twc);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【修改】叙词表范畴【" + categoryName
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【修改】叙词表范畴【" + categoryName
						+ "】成功！", 0);
			}

			count = 1;
		}
		if ("0".equals(id)) {
			int logTime = 0;
			try {
				iWordService.saveThesauriWordCategory(twc);
			} catch (Exception e) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】叙词表范畴【" + categoryName
						+ "】失败！请检查数据是否正确！", 1);
				logTime = 1;
				e.printStackTrace();
			}
			if (logTime == 0) {
				this.Log(logUser.getId(), "general_data", null, null, "【"
						+ logUser.getNickname() + "】【新增】叙词表范畴【" + categoryName
						+ "】成功！", 0);
			}

			count = 2;
		}
		String result = "{\"count\":" + count + "}";
		// System.out.println("resultadd   插入  更新：" + result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 叙词表 获取范畴管理更新内容
	@RequestMapping("thesauriWordCategoryEditShow")
	public void toThesauriWordCategoryEditShow(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		HashMap<String, Object> dMap = new HashMap<String, Object>();
		ThesauriWordCategory twc = iWordService
				.findThesauriWordCategory(Integer.parseInt(id));
		if (twc != null) {
			dMap.put("id", twc.getId());
			dMap.put("categoryName", twc.getCategoryName());
			dMap.put("categorySid", twc.getCategorySid());
			if (!"0".equals(twc.getParentId())
					&& !"null".equals(twc.getParentId())) {
				ThesauriWordCategory twc2 = iWordService
						.findThesauriWordCategory(Integer.parseInt(twc
								.getParentId()));
				dMap.put("parentId", twc2.getId());
				dMap.put("parentName", twc2.getCategoryName());
			}
		}
		String result = formatToJson(dMap);
		// System.out.println("result  generalWordCategoryEditShow 获取更新内容:"+result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 叙词表 范畴管理 删除
	@RequestMapping("delThesauriWordCategory")
	public void toDelThesauriWordCategory(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		ThesauriWordCategory thesauriWordCategory = iWordService
				.findThesauriWordCategory(Integer.parseInt(id));
		int logTime = 0;
		User logUser = publicService.findUser((Integer) request.getSession()
				.getAttribute("userid"));
		try {
			iWordService.deleteThesauriWordCategory(thesauriWordCategory);
		} catch (Exception e) {
			this.Log(logUser.getId(), "general_data", null, null,
					"【" + logUser.getNickname() + "】【删除】叙词表范畴【"
							+ thesauriWordCategory.getCategoryName()
							+ "】失败！请检查数据是否正确！", 1);
			logTime = 1;
			e.printStackTrace();
		}
		if (logTime == 0) {
			this.Log(logUser.getId(), "general_data", null, null,
					"【" + logUser.getNickname() + "】【删除】叙词表范畴【"
							+ thesauriWordCategory.getCategoryName() + "】成功！",
					0);
		}

		String result = "{\"count\":" + logTime + "}";
		super.pringWriterToPage(result.toString(), "application/json", response);
	}

	// 图形化 显示 款目词参照项
	@RequestMapping("findthesauriWordReferenceTuXingHua")
	public void toKnowledgeDataProperty(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("find图形化");
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		// HashMap<String, String> queryParams = new HashMap<String, String>();
		String thesauriWordId = request.getParameter("thesauriWordId");
		String wordClasses = request.getParameter("wordClasses");
		// System.out.println("thesauriWordId  :"+thesauriWordId);
		String name = "";
		if (thesauriWordId != null && !"".equals(thesauriWordId)) {
			ThesauriWord thesauriWord1 = iWordService.findThesauriWord(Integer
					.parseInt(thesauriWordId)); // 款目词
			name = thesauriWord1.getWordName();
		} else {
			name = "+";
		}
		LinkedHashMap<String, Object> mp = null;
		mp = new LinkedHashMap<String, Object>();
		mp.put("category", 0);
		mp.put("name", name);
		mp.put("value", 9);
		mp.put("label", name);
		r.add(mp);
		HashMap<String, Object> queryRelationParams = new LinkedHashMap<String, Object>();
		queryRelationParams.put("=,thesauri_word_module_id", wordClasses);
		List<ThesauriWordRelation> thesauriWordRelationList = iWordService.getThesauriWordRelation(queryRelationParams, 1, iWordService.getThesauriWordRelationCount(queryRelationParams));
		String str = "";
		String str2 = "";
		LinkedHashMap<String, Object> keyValue = new LinkedHashMap<String, Object>(); 
		for (int i = 0; i < thesauriWordRelationList.size(); i++) {
		    ThesauriWordRelation thesauriWordRelation = thesauriWordRelationList.get(i);
		    str += thesauriWordRelation.getNameZh()+"("+thesauriWordRelation.getNameEn()+"),";
		    str2 +="+("+thesauriWordRelation.getNameEn()+"),";
		    keyValue.put(thesauriWordRelation.getNameEn(), thesauriWordRelation.getNameZh()+"("+thesauriWordRelation.getNameEn()+")");
		}
		if(str != null && !"".equals(str)){
		    str = str.substring(0, str.length()-1);
		}
		if(str2 != null && !"".equals(str2)){
		    str2 = str2.substring(0, str2.length()-1);
		}
		String strType[] = str.split(",");
		String strType2[] = str2.split(",");
		for (int i = 0; i < strType.length; i++) {
			mp = new LinkedHashMap<String, Object>();
			mp.put("category", 1);
			mp.put("name", strType[i]);
			mp.put("value", 7);
			mp.put("source", name);
			mp.put("target", strType[i]);
			mp.put("weight", 6);
			r.add(mp);
			mp = new LinkedHashMap<String, Object>();
			mp.put("category", 2);
			mp.put("name", strType2[i]);
			mp.put("value", 6);
			mp.put("source", strType[i]); // 起点
			mp.put("target", strType2[i]); // 目标
			mp.put("weight", 4);
			r.add(mp);
		}
		if (thesauriWordId != null && !"".equals(thesauriWordId)) {
			HashMap<String, Object> queryParams = new LinkedHashMap<String, Object>();
			queryParams.put("=,thesauriWordId", thesauriWordId);
			int count = iWordService.getThesauriWordReferenceCount(queryParams);
			List<ThesauriWordReference> list = iWordService.getThesauriWordReference(queryParams, 1, count);
			for (ThesauriWordReference m : list) {
				ThesauriWord thesauriWord = iWordService.findThesauriWord(Integer.parseInt(m.getReferenceWordId()));
				mp = new LinkedHashMap<String, Object>();
				mp.put("category", 3);
				mp.put("value", 6);
				mp.put("weight", 4);
				mp.put("thesauriWordId", thesauriWordId);
				mp.put("name", thesauriWord.getWordName());
				mp.put("target", thesauriWord.getWordName());
				mp.put("id", thesauriWord.getId());
				mp.put("source", keyValue.get(m.getReferenceRelationLabel()));
				r.add(mp);
			}
		}
		String result = formatToJson(r);
		// System.out.println(result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	//下级子类
	@RequestMapping("queryjunoirZTree")
	public void queryjunoirZTree(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String type = request.getParameter("type");
		List<HashMap<String, Object>> junoirList = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp =null;
		HashMap<String, Object> queryParamsTwo = null;
		if("0".equals(type)){
			//父级
			ThesauriWord thesauriWord= iWordService.findThesauriWord(Integer.parseInt(id));
			mp =new LinkedHashMap<String, Object>();
			mp.put("id", thesauriWord.getId());
			mp.put("name", thesauriWord.getWordName());
			mp.put("pId", "0");
			junoirList.add(mp);
			
			HashMap<String, Object> queryParams = new LinkedHashMap<String, Object>();
			queryParams.put("=,word_pid", id);
			int count =iWordService.getThesauriWordCount(queryParams);
			List<ThesauriWord> thesauriWordList =iWordService.getThesauriWord(queryParams,1,count);
			for (int i = 0; i < thesauriWordList.size(); i++) {
				ThesauriWord subclass =thesauriWordList.get(i);
				mp = new LinkedHashMap<String, Object>();
				mp.put("id", subclass.getId());
				mp.put("name", subclass.getWordName());
				mp.put("pId", subclass.getWordPid());
				queryParamsTwo = new LinkedHashMap<String, Object>();
				queryParamsTwo.put("=,word_pid", subclass.getId());
	            int downCount =iWordService.getThesauriWordCount(queryParamsTwo);
	            if(downCount == 0){
	                mp.put("isParent", false);
	            }else{
	                mp.put("isParent", true); 
	            }
				junoirList.add(mp);
			}
		}else{
			HashMap<String, Object> queryParams = new LinkedHashMap<String, Object>();
			queryParams.put("=,wordPid", id);
			int count =iWordService.getThesauriWordCount(queryParams);
			List<ThesauriWord> thesauriWordList =iWordService.getThesauriWord(queryParams,1,count);
			for (int i = 0; i < thesauriWordList.size(); i++) {
				ThesauriWord subclass =thesauriWordList.get(i);
				mp = new LinkedHashMap<String, Object>();
				mp.put("id", subclass.getId());
				mp.put("name", subclass.getWordName());
				mp.put("pId", subclass.getWordPid());
				queryParamsTwo = new LinkedHashMap<String, Object>();
                queryParamsTwo.put("=,word_pid", subclass.getId());
                int downCount =iWordService.getThesauriWordCount(queryParamsTwo);
                if(downCount == 0){
                    mp.put("isParent", false);
                }else{
                    mp.put("isParent", true); 
                }
				junoirList.add(mp);
			}
		}
		String result = formatToJson(junoirList);
		// System.out.println("result  【zTree】  :" + result);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	//上级子类
	@RequestMapping("queryWpWord")
	public void queryWpWord(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String upWord="";
		ThesauriWord thesauriWord= iWordService.findThesauriWord(Integer.parseInt(id));
		if(null != thesauriWord.getWordPid() && !"".equals(thesauriWord.getWordPid())){
			ThesauriWord pidThesauriWord = iWordService.findThesauriWord(thesauriWord.getWordPid());
			upWord = pidThesauriWord.getWordName();
		}
		LinkedHashMap<String, Object> r = new LinkedHashMap<String, Object>();
		r.put("upWord", upWord);
		String result = formatToJson(r);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	/**
	 * 日志管理
	 * 
	 * @throws UnknownHostException
	 * */
	// 日志查询
	@RequestMapping("findAllLog")
	@ResponseBody
	public void findAllLog(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// System.out.println("findallDict");
		Integer pageNumber = 15;
		Integer pageSize = 1;
		if (request.getParameter("page") != null) {
			pageSize = Integer.parseInt(request.getParameter("page"));
		} else {
			pageSize = 1;
		}
		String logType = request.getParameter("logType");
		String logText = request.getParameter("logText");
		String ipAddRess = request.getParameter("ipAddRess");
		String userId = request.getParameter("userId");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if (logType != null && !"".equals(logType)) {
			queryParams.put("=,log_type", logType);
		}
		if (logText != null && !"".equals(logText)) {
			queryParams.put("%,log_text", logText);
		}
		if (ipAddRess != null && !"".equals(ipAddRess)) {
			queryParams.put("=,create_ip_address", ipAddRess);
		}
		if (userId != null && !"".equals(userId)) {
			queryParams.put("=,create_user_id", userId);
		}
		if (startTime != null && !"".equals(startTime)) {
			queryParams.put(">=,create_time", startTime);
		}
		if (endTime != null && !"".equals(endTime)) {
			queryParams.put("<=,create_time", endTime);
		}
		queryParams.put("^,create_time", "desc");
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		List<Log> list = publicService.getLog(queryParams, pageSize, pageNumber);
		long page = (int) Math.ceil(Double.valueOf(publicService.getLogCount(queryParams)) / 15);

		for (int i = 0; i < list.size(); i++) {
			Log log = list.get(i);
			if (log != null) {
				mp = new LinkedHashMap<String, Object>();
				mp.put("id", log.getId());
				mp.put("logType", log.getLogType());
				mp.put("logText", log.getLogText());
				mp.put("createTime", log.getCreateTime());
				if (log.getCreateUserId() != 0) {
					User u = publicService.findUser(log.getCreateUserId());
					if (u != null) {
						mp.put("createUserId", log.getCreateUserId());
						mp.put("createUserName", u.getUsername());
					}
				}
				mp.put("createIpAddress", log.getCreateIpAddress());
				mp.put("classesId", log.getClassesId());
				mp.put("dataId", log.getDataId());
				mp.put("logStatus", log.getLogStatus());
				r.add(mp);
			}
		}
		String result = formatToJson(r);
		// System.out.println("result:" +result);
		StringBuffer sb = new StringBuffer();
		int listsize = list.size();
		sb.append("{\"listsize\":" + listsize + ",");
		sb.append("\"pageSize\":" + page + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 首页展示 数据
	@RequestMapping("jiagongDataCount")
	public void tojiagongDataCount(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		LinkedHashMap<String, Object> mp = null;
		Integer departmentid = (Integer) request.getSession().getAttribute(
				"departmentid");
		Integer userid = (Integer) request.getSession().getAttribute("userid");
		User upUser = publicService.findUser(userid);
		Integer pageNumber = 10;
		Integer pageSize = 1;
		if (request.getParameter("page") != null) {
			pageSize = Integer.parseInt(request.getParameter("page"));
		} else {
			pageSize = 1;
		}
		List<User> list = publicService.getUser(null, pageSize, pageNumber);
		int j = 0;
		for (int k = 0; k < list.size(); k++) {
			User u = list.get(k);

			if (Integer.parseInt(upUser.getId().toString()) == 1) {
				j++;
				Department d = publicService
						.findDepartment(u.getDepartmentId());
				mp = new LinkedHashMap<String, Object>();
				mp.put("userName", u.getUsername());
				mp.put("departmentName", d.getName());
				HashMap<String, Object> queryParams = new HashMap<String, Object>();
				queryParams.put("=,userId", u.getId());
				List<UserGroupUser> listUR = publicService
						.getUserGroupUser(queryParams);
				String userGroupName = "";
				for (UserGroupUser ugu : listUR) {
					UserGroup ug = publicService.findUserGroup(ugu
							.getUserGroupId());
					userGroupName += ug.getName() + "；";
				}
				if (!userGroupName.equals("")) {
					userGroupName = userGroupName.substring(0,
							userGroupName.length() - 1);
				}

				mp.put("userGroupName", userGroupName);
				Long Zhoucount = 0L;
				Long Ricount = 0L;
				Long Yuecount = 0L;
				Long Niancount = 0L;
				List<Classes> list1 = publicService.getClasses();
				for (int i = 0; i < list1.size(); i++) {
					Classes Classes1 = list1.get(i);
					if (Classes1.getDisplay() == 1) {
						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy-MM-dd");
						Calendar c = Calendar.getInstance();
						int weekday = c.get(7) - 1;
						c.add(5, -weekday);
						String startTime = sdf.format(c.getTime())
								+ " 00:00:00";// 本周开始时间
						c.add(5, 6);
						String endTime = sdf.format(c.getTime()) + " 23:59:59";// 本周结束时间
						// System.out.println(startTime+"   《————周————》   "+endTime);
						Long Zhoucountold = dynamicService.getDynamicCount(
								Classes1.getNameEn(), u.getId().toString(),
								startTime, endTime);
						Zhoucount = Zhoucount + Zhoucountold;
						Date date = new Date();
						startTime = sdf.format(date) + " 00:00:00";// 本日开始时间
						endTime = sdf.format(date) + " 23:59:59";// 本日结束时间
						// System.out.println(startTime+"   《————日————》   "+endTime);
						Long Ricountold = dynamicService.getDynamicCount(
								Classes1.getNameEn(), u.getId().toString()
										.toString(), startTime, endTime);
						Ricount = Ricount + Ricountold;
						c.set(Calendar.DATE, 1);
						startTime = sdf.format(c.getTime()) + " 00:00:00"; // 月
																			// 开始
						c.add(Calendar.MONTH, 1);
						c.add(Calendar.DATE, -1);
						endTime = sdf.format(c.getTime()) + " 23:59:59";// 月
																		// 结束
						// System.out.println(startTime+"   《————月————》   "+endTime);
						Long Yuecountold = dynamicService.getDynamicCount(
								Classes1.getNameEn(), u.getId().toString()
										.toString(), startTime, endTime);
						Yuecount = Yuecount + Yuecountold;
						c.set(Calendar.MONTH, 0);
						c.set(Calendar.DATE, 1);
						startTime = sdf.format(c.getTime()) + " 00:00:00"; // 年
						c.set(Calendar.MONTH, 11);
						c.set(Calendar.DATE, 31);
						endTime = sdf.format(c.getTime()) + " 23:59:59";// 年
																		// 结束
						Long Niancountold = dynamicService.getDynamicCount(
								Classes1.getNameEn(), u.getId().toString()
										.toString(), startTime, endTime);
						Niancount = Niancount + Niancountold;
						// System.out.println(startTime+"   《————年————》   "+endTime);
					}
				}
				mp.put("Zhoucount", Zhoucount);
				mp.put("Ricount", Ricount);
				mp.put("Yuecount", Yuecount);
				mp.put("Niancount", Niancount);
				r.add(mp);
			} else {
				Department d = publicService
						.findDepartment(u.getDepartmentId());
				if (d.getId() == departmentid) {
					j++;
					mp = new LinkedHashMap<String, Object>();
					mp.put("userName", u.getUsername());
					mp.put("departmentName", d.getName());
					HashMap<String, Object> queryParams = new HashMap<String, Object>();
					queryParams.put("=,userId", u.getId());
					List<UserGroupUser> listUR = publicService
							.getUserGroupUser(queryParams);
					String userGroupName = "";
					for (UserGroupUser ugu : listUR) {
						UserGroup ug = publicService.findUserGroup(ugu
								.getUserGroupId());
						userGroupName += ug.getName() + "；";
					}
					if (!userGroupName.equals("")) {
						userGroupName = userGroupName.substring(0,
								userGroupName.length() - 1);
					}

					mp.put("userGroupName", userGroupName);
					Long Zhoucount = 0L;
					Long Ricount = 0L;
					Long Yuecount = 0L;
					Long Niancount = 0L;
					List<Classes> list1 = publicService.getClasses();
					for (int i = 0; i < list1.size(); i++) {
						Classes Classes1 = list1.get(i);
						if (Classes1.getDisplay() == 0) {
							SimpleDateFormat sdf = new SimpleDateFormat(
									"yyyy-MM-dd");
							Calendar c = Calendar.getInstance();
							int weekday = c.get(7) - 1;
							c.add(5, -weekday);
							String startTime = sdf.format(c.getTime())
									+ " 00:00:00";// 本周开始时间
							c.add(5, 6);
							String endTime = sdf.format(c.getTime())
									+ " 23:59:59";// 本周结束时间
							// System.out.println(startTime+"   《————周————》   "+endTime);
							Long Zhoucountold = dynamicService.getDynamicCount(
									Classes1.getNameEn(), u.getId().toString(),
									startTime, endTime);
							Zhoucount = Zhoucount + Zhoucountold;
							Date date = new Date();
							startTime = sdf.format(date) + " 00:00:00";// 本日开始时间
							endTime = sdf.format(date) + " 23:59:59";// 本日结束时间
							// System.out.println(startTime+"   《————日————》   "+endTime);
							Long Ricountold = dynamicService.getDynamicCount(
									Classes1.getNameEn(), u.getId().toString()
											.toString(), startTime, endTime);
							Ricount = Ricount + Ricountold;
							c.set(Calendar.DATE, 1);
							startTime = sdf.format(c.getTime()) + " 00:00:00"; // 月
																				// 开始
							c.add(Calendar.MONTH, 1);
							c.add(Calendar.DATE, -1);
							endTime = sdf.format(c.getTime()) + " 23:59:59";// 月
																			// 结束
							// System.out.println(startTime+"   《————月————》   "+endTime);
							Long Yuecountold = dynamicService.getDynamicCount(
									Classes1.getNameEn(), u.getId().toString()
											.toString(), startTime, endTime);
							Yuecount = Yuecount + Yuecountold;
							c.set(Calendar.MONTH, 0);
							c.set(Calendar.DATE, 1);
							startTime = sdf.format(c.getTime()) + " 00:00:00"; // 年
							c.set(Calendar.MONTH, 11);
							c.set(Calendar.DATE, 31);
							endTime = sdf.format(c.getTime()) + " 23:59:59";// 年
																			// 结束
							Long Niancountold = dynamicService.getDynamicCount(
									Classes1.getNameEn(), u.getId().toString()
											.toString(), startTime, endTime);
							Niancount = Niancount + Niancountold;
							// System.out.println(startTime+"   《————年————》   "+endTime);
						}
					}
					mp.put("Zhoucount", Zhoucount);
					mp.put("Ricount", Ricount);
					mp.put("Yuecount", Yuecount);
					mp.put("Niancount", Niancount);
					r.add(mp);
				}
			}

		}
		String result = formatToJson(r);
		// System.out.println("result:" +result);
		StringBuffer sb = new StringBuffer();
		sb.append("{\"listsize\":" + j + ",");
		sb.append("\"pageSize\":"
				+ (int) Math.ceil(Double.valueOf(j) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}

	// 日志导出下载
	@RequestMapping("logdownload")
	public void logDownload(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String logType = request.getParameter("logType");
		String logText = request.getParameter("logText");
		String ipAddRess = request.getParameter("ipAddRess");
		String userId = request.getParameter("userId");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		String downType = request.getParameter("downType");
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		if (logType != null && !"".equals(logType)) {
			queryParams.put("=,log_type", logType);
		}
		if (logText != null && !"".equals(logText)) {
			queryParams.put("%,log_text", logText);
		}
		if (ipAddRess != null && !"".equals(ipAddRess)) {
			queryParams.put("=,create_ip_address", ipAddRess);
		}
		if (userId != null && !"".equals(userId)) {
			queryParams.put("=,create_user_id", userId);
		}
		if (startTime != null && !"".equals(startTime)) {
			queryParams.put(">=,create_time", startTime);
		}
		if (endTime != null && !"".equals(endTime)) {
			queryParams.put("<=,create_time", endTime);
		}
		queryParams.put("^,create_time", "desc");
		if("xml".equals(downType)){
			logDownloadXml(request,response,queryParams);
		}else{
			logDownloadExcel(request,response,queryParams);
		}
	}
	//日志导出Xml
	public void logDownloadXml(HttpServletRequest request,HttpServletResponse response,HashMap<String, Object> queryParams) throws Exception {
		DocumentBuilderFactory fct = DocumentBuilderFactory.newInstance();
		DocumentBuilder bui;
		try {
			// 驱动
			bui = fct.newDocumentBuilder();
			// 创建对象
			Document doc = bui.newDocument();
			// 设置根目录
			Element log_data = doc.createElement("log_data");

			Integer count = publicService.getLogCount(queryParams);
			// System.out.println(cont1);
			List<Log> logs = publicService.getLog(queryParams, 1, count);
			// System.out.println(generalWords.size());
			for (Log ls : logs) {
				// 设置二级目录
				Element log_word = doc.createElement("log_word");

				// 二级标题属性
				Attr id = doc.createAttribute("id");
				// 赋值

				id.setNodeValue(ls.getId().toString());
				// 写入二级目录
				log_word.setAttributeNode(id);
				// 创建节点
				Element log_type = doc.createElement("log_type");
				// 赋值
				log_type.setTextContent(ls.getLogType());

				Element create_time = doc.createElement("create_time");
				create_time.setTextContent(ls.getCreateTime());

				Element create_user_id = doc.createElement("create_user_id");
				create_user_id.setTextContent(ls.getCreateUserId().toString());

				Element create_ip_address = doc
						.createElement("create_ip_address");
				create_ip_address.setTextContent(ls.getCreateIpAddress());

				if (ls.getClassesId() != null) {
					Element classes_id = doc.createElement("classes_id");
					classes_id.setTextContent(ls.getClassesId());
					log_word.appendChild(classes_id);
				}
				if (ls.getDataId() != null) {
					Element data_id = doc.createElement("data_id");
					data_id.setTextContent(ls.getDataId());
					log_word.appendChild(data_id);
				}

				Element log_text = doc.createElement("log_text");
				log_text.setTextContent(ls.getLogText());

				Element log_status = doc.createElement("log_status");
				log_status.setTextContent(ls.getLogStatus().toString());
				// 将节点写入二级目录
				log_word.appendChild(log_type);
				log_word.appendChild(create_time);
				log_word.appendChild(create_user_id);
				log_word.appendChild(create_ip_address);
				log_word.appendChild(log_text);
				log_word.appendChild(log_status);

				// 写入上级目录
				log_data.appendChild(log_word);
			}
			// 目录保存到doc
			doc.appendChild(log_data);

			// step9:获得一个TransformerFactory对象
			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
			// step10:获得一个Transformer对象
			Transformer transformer = transformerFactory.newTransformer();
			// step11:把document对象用一个DOMSource对象包装起来
			Source xmlSource = new DOMSource(doc);
			// 获取服务器地址
			ServletContext sc = request.getSession().getServletContext();
			String dir = sc.getRealPath("/XMLFile/");
			File dirFile = new File(dir);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			String random = System.nanoTime() + ".xml";
			File downFile = new File(dirFile, random);
			Result outputTarget = new StreamResult(downFile);
			// step13:生成相应的xml文件
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty(
					"{http://xml.apache.org/xslt}indent-amount", "4");
			transformer.transform(xmlSource, outputTarget);

			// 下载文件
			FileDownloadUtil.download(downFile, "日志.xml", request, response);

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}
	//日志导出Excel
	public void logDownloadExcel(HttpServletRequest request,HttpServletResponse response,HashMap<String, Object> queryParams) throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		String path =  XxlConfClient.get("dal.file.path", "") +"/";
		Integer count = publicService.getLogCount(queryParams);
		List<Log> logs = publicService.getLog(queryParams, 1, count);
		List<HashMap<String, Object>> listData = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> map = null;
		for (int i = 0; i < logs.size(); i++) {
			Log log = logs.get(i);
			map = new HashMap<String, Object>();
			map.put("id", log.getId());
			map.put("logType", (null != log.getLogType()) ? log.getLogType() : "");
			map.put("createTime", (null != log.getCreateTime() ) ? log.getCreateTime() : "");
			map.put("createUserId",  (null != log.getCreateUserId() ) ? log.getCreateUserId() : "");
			map.put("createIpAddress", (null != log.getCreateIpAddress() ) ? log.getCreateIpAddress() : "");
			map.put("classesId", (null != log.getClassesId() ) ? log.getClassesId() : "");
			map.put("dataId", (null != log.getDataId() ) ? log.getDataId() : "");
			map.put("logText", (null != log.getLogText() ) ? log.getLogText() : "");
			map.put("logStatus", (null != log.getLogStatus() ) ? log.getLogStatus() : "");
			listData.add(map);
		}
		DBUtils.writeExcel(path + "log.xls", listData, 1);
		downloadkk(request, response, "log.xls", path);
	}
}
